Подскажите пожалуйста как делается проверка req query если их очень много, есть ли варианты с коротким кодом, ибо делать if для каждого элемента из req query не вариант.
Буду благодарен за ответ
async getAll(req: Request, res: Response, next: NextFunction) {
let { typeId, categoryId, pageLimit, page, colorway, sortBy } = req.query
page = page || (1 as any)
pageLimit = pageLimit || (10 as any)
//@ts-ignore
let offset = page * pageLimit - pageLimit
let products
if (!typeId && !categoryId && !colorway && !sortBy) {
//@ts-ignore
products = await Product.findAndCountAll({
distinct: true,
include: [
{
model: ProductVariant,
as: 'variant',
include: [
{
model: Image,
as: 'images',
limit: 1,
},
],
},
],
})
}
if (typeId && !categoryId && !colorway && !sortBy) {
//@ts-ignore
products = await Product.findAndCountAll({ where: { typeId }, limit: pageLimit, offset })
}
if (!typeId && categoryId && !sortBy && !colorway) {
//@ts-ignore
products = await Product.findAndCountAll({ where: { categoryId }, limit: pageLimit, offset })
}
if (typeId && categoryId && !sortBy && !colorway) {
//@ts-ignore
products = await Product.findAndCountAll({ where: { typeId, categoryId }, limit: pageLimit, offset })
}
if (!typeId && !categoryId && !sortBy && colorway) {
products = await Product.findAndCountAll({
// limit: pageLimit,
// offset,
where: {
//@ts-ignore
'$variant.color$': { [Op.eq]: colorway },
},
include: [
{
model: ProductVariant,
as: 'variant',
// limit: 4,
// order: [['createdAt', 'DESC']],
// attributes: [],
// required: false,
},
],
})
}
if (!typeId && !categoryId && !colorway && sortBy) {
console.log(sortBy)
switch (sortBy) {
case 'DESC':
products = await Product.findAndCountAll({
order: [['createdAt', 'DESC']],
include: [
{
model: ProductVariant,
as: 'variant',
},
],
})
break
case 'priceDesc':
products = await Product.findAndCountAll({
order: Sequelize.literal('max(variant.price) DESC'),
include: [
{
model: ProductVariant,
as: 'variant',
},
],
group: ['product.id', 'variant.id'],
})
break
case 'priceAsc':
products = await Product.findAndCountAll({
order: Sequelize.literal('max(variant.price) ASC'),
distinct: true,
include: [
{
model: ProductVariant,
as: 'variant',
},
],
group: ['product.id', 'variant.id'],
})
break
default:
break
}
}
return res.json(products)
}