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!
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 });
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With