Home > OS >  How access Response in Express outside Route controller
How access Response in Express outside Route controller

Time:12-27

I am using Express JS for backend API.

I need to simply use res object from custom service, not route controller.

Of course I am calling service function from controller and I know that I can easily pass res as an argument and access it, but I wonder if there is other case or maybe better practice.

const videoaskResponse = async (req, res, next) => {
  try {
    await webhookService.handleVideoaskResponse(req.body, res)

    res.status(200).json({ received: true })
  } catch (error) {
    next(error)
  }
}

Here's example how I handle that case.

CodePudding user response:

you are on the right track the best practice is to pass res as a function argument.

Another possible approach which is not industry standard is to return an object from webhookService.handleVideoaskResponse.

Then you can set the fields of the res object to the fields from that object returned from your function call. This would put the logic of editing the res object in the router rather than the service.

  • Related