Matt
Matt

Reputation: 91

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!

Upvotes: 5

Views: 4362

Answers (1)

Matt
Matt

Reputation: 91

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 });
};

Upvotes: 4

Related Questions