Trying to retrieve a JSON from the route "/api/product" and display it using hbs on the "/product" route. The code seems to be working, but is it done correctly?
The router in this case is: '/api/product'
router.get('/', this.controller.renderProducts);
renderProducts = async (req, res) => {
try {
const docs = await this.ProductsDAO.getAll();
const products = docs.map((p) => {
return new ProductDTO(
p.id,
p.price,
p.stock
);
});
res.status(200).json({ product:products });
} catch (error) {
logger.error('Error rendering products', error);
res.status(400).send('Failed to render products');
}
};
Should I add this code to server.js for it to work properly?
app.get('/product', new RequestViews().getAllProducts)
class RequestViews {
constructor() {
this.url = 'http://localhost:8080/api/product';
}
getAllProducts = (req, res, next) => {
request.get(this.url, (err, response, body) => {
if (err) {
return next(err);
}
res.render('products', JSON.parse(body));
});
}
Thank you!