diff --git a/controllers/products.js b/controllers/products.js index e951761..5c1a6c6 100644 --- a/controllers/products.js +++ b/controllers/products.js @@ -10,6 +10,14 @@ router.get('/', rescue(async (_req, res) => { res.status(result.status).json({ products: [...result.productS] }); })); +router.get('/search', rescue(async (req, res) => { + const { name } = req.query; + const result = await products.getAllFiltered(name); + + res.status(result.status).json({ products: [...result.products], + message: result.message }); +})); + router.get('/:id', async (req, res) => { const { id } = req.params; diff --git a/models/products.js b/models/products.js index cb559cf..5cdd0a4 100644 --- a/models/products.js +++ b/models/products.js @@ -27,8 +27,8 @@ const getAllFiltered = async (query) => { const db = await connection(); const products = await db.collection('products') - .find({ name: { $regex: `/${query}/i` } }).toArray(); - + .find({ name: { $regex: `${query}`, $options: 'i' } }).toArray(); + return products; }; diff --git a/services/products.js b/services/products.js index 1e3745a..59d757a 100644 --- a/services/products.js +++ b/services/products.js @@ -50,10 +50,10 @@ const getAll = async () => { }; const getAllFiltered = async (query) => { - const products = await models.getAll(query); - - if (!products) { - return { + const products = await models.getAllFiltered(query); + + if (products.length === 0) { + return { status: STATUS_NOT_FOUND, message: MSG_NOT_FOUND, products,