feat: Add 'getAllFiltered' in CONTROLLER and MODEL

This commit is contained in:
Michel Pereira 2021-12-27 08:40:59 -03:00
parent a29e4edfe0
commit 4ab023be48
3 changed files with 32 additions and 4 deletions

View file

@ -27,7 +27,7 @@ router.get('/:id', async (req, res) => {
const { _id, name, quantity, price, thumbnail, description } = result;
const productData = { id: _id, name, quantity, price, thumbnail, description };
res.status(200).json(productData);
res.status(OK).json(productData);
});
router.post('/', rescue(async (req, res) => {
@ -81,7 +81,7 @@ router.delete('/:id', rescue(async (req, res) => {
const { _id, name, quantity } = result;
res.status(200).json({ id: _id, name, quantity });
res.status(OK).json({ id: _id, name, quantity });
}));
module.exports = router;

View file

@ -18,11 +18,20 @@ const getByName = async (name) => connection()
const getAll = async () => connection()
.then(async (db) => {
const productS = await db.collection('products').find().toArray();
const products = await db.collection('products').find().toArray();
return productS;
return products;
});
const getAllFiltered = async (query) => {
const db = await connection();
const products = await db.collection('products')
.find({ name: { $regex: `/${query}/i` } }).toArray();
return products;
};
const getById = async (id) => connection()
.then(async (db) => {
const product = await db.collection('products').findOne(new ObjectId(id));
@ -62,4 +71,5 @@ module.exports = {
update,
updateQtd,
deleteIt,
getAllFiltered,
};

View file

@ -3,7 +3,10 @@ const validators = require('../utils/validators');
const STATUS_OK = 200;
const STATUS_UNPROCESSABLE_ENTITY = 422;
const STATUS_NOT_FOUND = 404;
const CODE_INVALID_DATA = 'invalid_data';
const MSG_NOT_FOUND = 'No match found';
const MSG_FOUND = 'Match found';
const MSG_WRONG_ID = 'Wrong id format';
const create = async (productData) => {
@ -46,6 +49,20 @@ const getAll = async () => {
return { status: STATUS_OK, productS };
};
const getAllFiltered = async (query) => {
const products = await models.getAll(query);
if (!products) {
return {
status: STATUS_NOT_FOUND,
message: MSG_NOT_FOUND,
products,
};
}
return { status: STATUS_OK, message: MSG_FOUND, products };
};
const getById = async (id) => {
// "id" validation:
@ -137,4 +154,5 @@ module.exports = {
getById,
update,
deleteIt,
getAllFiltered,
};