Изучаю Express.js и не могу ни как понять как объектам фильтров добавить свойство disabled: true если при добавлении этого фильтра к уже выбранными не будет товаров с данным набором характеристик.
База данных PostgreSQL orm sequelize.js
связи: одна Models к многим Product. один Product к многим Specification
const { Product, Models, Specification } = require('../models/models');
const { Sequelize } = require('sequelize');
class productController {
async getAll(req, res) {
const { subCategoryId, models, specifications, minPrice, maxPrice } = req.query;
if (!subCategoryId) {
return res.status(400).json({ error: 'subCategoryId is required' });
}
const modelCondition = models ? { model: { [Sequelize.Op.in]: models.split(',') } } : {};
const specificationCondition = specifications
? { specification: { [Sequelize.Op.in]: specifications.split(',') } }
: {};
const priceCondition = {};
if (minPrice && maxPrice) {
priceCondition.price = {
[Sequelize.Op.and]: [
{ [Sequelize.Op.gte]: minPrice },
{ [Sequelize.Op.lte]: maxPrice },
],
};
} else if (minPrice) {
priceCondition.price = { [Sequelize.Op.gte]: minPrice };
} else if (maxPrice) {
priceCondition.price = { [Sequelize.Op.lte]: maxPrice };
}
try {
const products = await Product.findAll({
where: { ...priceCondition },
include: [
{
model: Models,
where: { subCategoryId, ...modelCondition },
attributes: {
exclude: ['updatedAt', 'createdAt', 'img', 'subCategoryId'],
},
},
{
model: Specification,
where: { ...specificationCondition },
attributes: {
exclude: [
'updatedAt',
'createdAt',
'productId',
'specificationGroupId',
],
},
},
],
attributes: {
exclude: ['updatedAt', 'createdAt'],
},
});
res.json(products);
} catch (error) {
console.error('Error fetching products by subcategory ID:', error);
res.status(500).json({ error: 'An error occurred while fetching products' });
}
}
async getOne(req, res) {}
}
module.exports = new productController();
Контролер получения фильтров
const { SpecificationGroup, Specification, Models } = require('../models/models');
class FiltersController {
async getAll(req, res) {
const { subCategoryId, models, specifications } = req.query;
const specification = await SpecificationGroup.findAll({
where: { subCategoryId },
attributes: ['id', 'name'],
include: [
{
model: Specification,
attributes: ['id', 'specification', 'value'],
},
],
});
const uniqueSpecifications = specification.map((group) => {
const uniqueSpecs = group.specifications.reduce((acc, spec) => {
const exists = acc.some((item) => item.specification === spec.specification);
if (!exists) {
acc.push(spec);
}
return acc;
}, []);
const plainGroup = group.get({ plain: true }); // Получаем "плоскую" версию объекта
return {
...plainGroup,
specifications: uniqueSpecs,
};
});
const model = await Models.findAll({
where: { subCategoryId },
});
res.json({
specifications: uniqueSpecifications,
models: model,
});
}
}
module.exports = new FiltersController();