0

I want to send a custom json response on each request at the end like:

{
  "message": "Something",
  "type": "success",
  "payload": /*object, array, anything else */
}

What I can do is at the end of each request use:

res.status(200).json({message: 'Something', type: 'success', payload});

If for some reason I want my responses to have another format, I have to go and change each res.json, which is bad.

But since I know all my responses will have this format, is there any way to create a middleware and pass some variables like payload, message, type which gets executed at the end of each request?

Ghost
  • 401
  • 3
  • 15
  • Simple refactoring: `res.status(200).json(generateReply({message: 'Something', type: 'success' }));` Now just add whatever you want inside the `generateReply` function and return it. –  Oct 14 '21 at 17:26
  • @ChrisG I know this can be done, but since I know every response will have a specific structure, I want to not have to write res.status.json... for each one. I already know that at the end of a request I want to send a formatted response. I was wondering if there is a centralized way of doing it. – Ghost Oct 14 '21 at 17:28
  • You can also do `reply(res, {message: 'Something', type: 'success' })` or whatever, then call `res.status(200).json(...);` inside the `reply` function. –  Oct 14 '21 at 17:29
  • Check also an error handling: https://expressjs.com/en/guide/error-handling.html –  Oct 14 '21 at 17:30
  • @ChrisG this is redundant imo. You already know res will be the one who will have the formatted json. I am searching for a way to not have to pass res to a function you create. Maybe there is something express has built in. – Ghost Oct 14 '21 at 17:31
  • @DamianCyntler this is about error handling. I know I can pass next(something) and I will be considered an error. – Ghost Oct 14 '21 at 17:33
  • `res` is not the same "thing" each time though, it's the dynamically created response object. You have to pass it along to your custom function afaik. I guess you could store a reference to it in a middleware, then use the reference in your custom function. –  Oct 14 '21 at 17:34
  • @ChrisG I saw some examples where you can run a middleware at the end of each request and modify res.send, but I don't know if that can be applied here and made to work with variable arguments. – Ghost Oct 14 '21 at 17:36
  • @Ghost, check this: https://www.npmjs.com/package/express-mung. –  Oct 14 '21 at 17:38
  • How may routes to do have exactly? Are you sure trying to find a way not to have pass `res` is worth the time you're spending on this? –  Oct 14 '21 at 17:40
  • @ChrisG It's more about if it can be done than if I really need it. – Ghost Oct 14 '21 at 17:42
  • Make a middleware that wraps the .json function like here https://stackoverflow.com/questions/34114880/override-node-js-express-response-method – Rani Sharim Oct 14 '21 at 17:47

2 Answers2

0

It is possible to create a midleware for the reponse

router.get('/some-route', controller.someFunction, resposeMiddleware)

You would need to pass the response as an argument on the next call

someFunction (req, res, next) => {
    res.local.payload = {/* some data */}
    next()
}

the resposeMiddleware would be something like this

const resposeMiddleware = (req, res) => {
      const { payload } =  res.local
      res.status(200).json({message: 'Something', type: 'success', payload})
}
joaojvt
  • 11
  • 1
0

Create a helper method like bellow (successResponse.js). You can also set any property to default.

    successResponse = (res, statusCode, message, data) => {
      res.status(statusCode || 200).json({
      code: statusCode || 200,
      message: message || "success",
      data: data || {},
    });
   };

   module.exports = successResponse;

now in your controller just import successResponse and use it like

successResponse(res, 200, "Your Success message", data);
Brijesh Dave
  • 315
  • 2
  • 9