Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express middleware to wrap response

I'm implementing an API where the result needs to be return wrapped by a result key, as such

{
  result: [
    {
      id: 1,
      name: "Bob"
    }
  ]
}

What I'd like to do is add a piece of middleware (if possible) that does this wrapping to every response without having to think about it every time. What would be the best way to accomplish this? I could see modifying response.body and then calling next() instead of doing res.send(obj) (what I'm doing now).

Thanks!

like image 227
Matt Avatar asked Sep 27 '22 07:09

Matt


1 Answers

I ended up extending the response object to add a new function (used like res.sendWrapped(data)) per In Express and Node.js, is it possible to extend or override methods of the response object? as such:

express.response.sendWrapped = function(obj) {
    return this.send({ result: obj });
};
like image 117
Matt Avatar answered Oct 12 '22 23:10

Matt