implemented product lookup by name
This commit is contained in:
@@ -23,4 +23,16 @@ module.exports = class ProductModel {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,23 @@ module.exports = (app) => {
|
||||
app.use('/api/product', router);
|
||||
|
||||
router.get('/', async (req, res, next) => {
|
||||
const { name } = req.query;
|
||||
|
||||
if (name) {
|
||||
try {
|
||||
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);
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/:productId', async(req, res, next) => {
|
||||
|
||||
@@ -22,4 +22,14 @@ module.exports = class ProductService {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user