implemented product lookup by name

This commit is contained in:
Mikayla Dobson
2022-09-27 16:54:32 -05:00
parent efa74d1c16
commit 388f3a5ba9
3 changed files with 38 additions and 5 deletions

View File

@@ -23,4 +23,16 @@ module.exports = class ProductModel {
throw new Error(e); throw new Error(e);
} }
} }
async findOneByName(name) {
try {
const q = `SELECT * FROM product WHERE name = $1;`;
const filter = [name];
const result = await db.query(q, filter);
if (result.rows.length) return result.rows[0];
return null;
} catch(e) {
throw new Error(e);
}
}
} }

View File

@@ -6,11 +6,22 @@ module.exports = (app) => {
app.use('/api/product', router); app.use('/api/product', router);
router.get('/', async (req, res, next) => { router.get('/', async (req, res, next) => {
try { const { name } = req.query;
const response = await ProductServiceInstance.getAll();
res.status(200).send(response); if (name) {
} catch(e) { try {
next(e); const response = await ProductServiceInstance.getOneByName(name);
res.status(200).send(response);
} catch(e) {
next(e);
}
} else {
try {
const response = await ProductServiceInstance.getAll();
res.status(200).send(response);
} catch(e) {
next(e);
}
} }
}) })

View File

@@ -22,4 +22,14 @@ module.exports = class ProductService {
throw new Error(e); throw new Error(e);
} }
} }
async getOneByName(name) {
try {
const result = await ProductInstance.findOneByName(name);
if (!result) throw createError(404, 'No products found.');
return result;
} catch(e) {
throw new Error(e);
}
}
} }