I am trying to filter products that fall within the price range of my selected query. The filter works well when I use it on other fields but starts acting funny when i include the price filter in the search Params.
This is my frontend code
interface SquarePageProps {
searchParams: {
creatorId?: string;
name?: string;
colors?: string[];
categoryId?: string;
price?: string[];
}
}
const products = await getProducts({
isFeatured: true,
name: searchParams.name,
colors: searchParams.colors,
categoryId: searchParams.categoryId,
price: searchParams.price,
})
This is where i collate my form information and append it to the search Params
const onSubmit = async (data: FilterFormValues) => {
const current = qs.parse(searchParams.toString());
const colorValues = selectedColors.map(selected => selected.value.charAt(0).toUpperCase() + selected.value.slice(1))
// @ts-ignore
let query = {
...current,
'categoryId': data.categoryId,
'colors': colorValues.length > 0 ? colorValues : null,
'subCategory': data.subCategory,
'price': [minPrice, maxPrice],
}
console.log(query)
const url = qs.stringifyUrl({
url: window.location.href,
query,
}, { skipEmptyString: true, skipNull: true, })
router.push(url)
form.reset();
};
Colors and Price are both array of strings.
This is my backend where i make the request;
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const storeId = '665a238f72ab3f9616e1a1d8';
const categoryId = searchParams.get('categoryId') || undefined;
const isFeatured = searchParams.get('isFeatured') || undefined;
const name = searchParams.get('name') || undefined;
const colorsQuery = searchParams.getAll('colors') || undefined;
const price = searchParams.getAll('price') || null;
// const minPrice = priceQuery[0] == '' ? '500' : priceQuery[0];
// const maxPrice = priceQuery[1] == '' ? '5000000' : priceQuery[1];
const products = await prismadb.product.findMany({
where: {
storeId,
categoryId,
isFeatured: isFeatured ? true : undefined,
isArchived: false,
price: {
gte: price[0] == '' ? 500 : parseInt(price[0], 10),
lte: price[1] == '' ? 500000 : parseInt(price[1], 10),
},
name,
colors: colorsQuery
? {
hasSome: colorsQuery,
}
: undefined,
},
include: {
category: true,
},
orderBy: {
createdAt: 'desc',
},
});
await prismadb.$disconnect();
return NextResponse.json(products);
} catch (error) {
console.log('[PRODUCTS_GET]', error);
return NextResponse.json('Network error, Please reload your page', {
status: 500,
});
}
}
It works in some instance, like if i use 600 as the maximum price but returns nothing when I use other ranges