Home > Back-end >  Return a res.json and get it with res.render in other router
Return a res.json and get it with res.render in other router

Time:07-05

Im working to return a JSON from the router "/api/product" but render the answer with hbs in the router "/product". The code works, but is it correct?

My router in this case is: '/api/product'

router.get('/', this.controlador.renderProducts);

renderProducts = async (req, res) => {
    try {
      const docs = await this.ProductsDAO.mostrarTodos();

      const productos = docs.map((p) => {
        return new ProductDTO(
          p.id,
          p.precio,
          p.stock
        );
      });

      res.status(200).json({ product:productos });
    } catch (error) {
      logger.error('Error al renderizar productos', error);
      res.status(400).send('Status: No se ha renderizar productos');
    }
  };

Is correct on server.js add this code for it?

app.get('/product', new RequestViews().getProductAll)

class RequestViews {
  constructor() {
    this.url = 'http://localhost:8080/api/product';
  }

 getProductAll = (req, res, next) => {
    request.get(this.url, (err, response, body) => {
      if (err) {
        return next(err);
      }
      res.render('products', JSON.parse(body));
    });
  }

Thanks!!

CodePudding user response:

There's no need to make internal HTTP requests within your Express app. Instead, encapsulate logic into re-usable functions.

For example, you can capture the mostrarTodos() and .map() in a function...

const getProducts = async () => {
  const docs = await ProductsDAO.mostrarTodos();

  const productos = docs.map((p) => new ProductDTO(p.id, p.precio, p.stock));
};

and call that from both route handlers

renderProducts = async (req, res) => {
  try {
    res.status(200).json({ product: await getProducts() });
  } catch (error) {
    logger.error("Error al renderizar productos", error);
    res.status(400).send("Status: No se ha renderizar productos");
  }
};
class RequestViews {
  getProductAll = (req, res, next) => {
    getProducts()
      .then((product) => {
        res.render("products", { product });
      })
      .catch(next);
  };
}
  • Related