3

I have the following GET call which works as intended, connecting to a couchbase db and performing some updates.

databaseRouter.put('/update/:id', (req, res) => {
  updateDocument(req, res);
});

export const updateDocument = (req, res) => {
  collection.get(req.params.id, (err, result) => {
    if (err) {
      res.status(404).send(err);
    } else {
      const document = result.value;
      document.product_id = req.body.id || document.product_id;
      collection.replace(req.params.id, document, (err) => {
        if (err) {
          res.status(500).send(err);
        }
      }).then(() => res.json(document));
    }
  }).catch(e => console.log(e));
}

This is for external clients to use.

But I want this to logic to be reusable within the project in another instance for batch processing. Not a rest call.

Thus I am looking to refactor the updateDocument function to return the document value or errors instead of performing res.send();

But I can't just modify as follows. result is undefined.

And I am also not gonna be able to maintain the status codes for errors.

Unless I explicitly return like a object with a key called status.

export const updateDocument = (req, res) => {
    .....
    }).then(() => document); // instead of }).then(() => res.json(document));
    .....
}

databaseRouter.put('/update/:id', (req, res) => {
  const result = updateDocument(req, res); // result is undefined
  res.send(result);
});

Is there a way I could elegantly extract the logic so that I can continue to achieve what I have for the GET call for clients

but also be able to reuse the same logic internally within the project?

kar
  • 4,791
  • 12
  • 49
  • 74
  • 1
    Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this appears to duplicate. – Dave Newton Feb 02 '23 at 20:53
  • What would you do for `req.params.id` and `req.body.id` in the batch processing call? – Matt Feb 03 '23 at 04:40

0 Answers0