Home > Software design >  How to use an endpoint as a function inside another function using express js
How to use an endpoint as a function inside another function using express js

Time:05-24

I want to get the shop if shop does not exist then call app.post() to add a new shop.

My app.post() it creates the shop successfully:

app.post('/shops/addShop', (req, res) => {
      const shop = {
        id: 'shop'   (shops.length   1),
        name: req.body.name,
        departmentList: [
        {
          id: 'd1',
          name: "department 1"
        },
        {
          id: 'd2',
          name: "department 2"
        },
        {
          id: 'd3',
          name: "department 3"
        }
        ]
      };
   
      shops.push(shop);
      res.send(shop);
});

How to implement getShop() by Id if exist otherwise create it by using app.post():

app.get('/shops/:id', (req, res) => {
   // how to code here
});

CodePudding user response:

You shouldn't call app.post() directly, that's an API controller, instead you want to have a separate function that performs this logic.

app.post('/shops', (req, res) => {
  res.send(createNewShop());
});

app.get('/shops/:id', (req, res) => {
  const shopExists = findShop(req.params.id);

  if (!shopExists) {
    return res.send(createNewShop());
  } else {
    // do something with your shop
  }
});
  • Related