Categories
express node.js

how to extend express js res object in NodeJs

Here is a simple route:

// get all users
app.get('/api/user/get-all', authenticated.yes, function(req, res) {
queryUsers.findAllUsers( function( users ){
res.json( users );
} );
});

The output would be the json returned from the “queryUsers.findAllUsers” function.

This is great, but i want to route all my json output through something more rigid so the output would be:

res.json({
success: true,
payload: users
});

This is really easy to do manually but means I have to write this out each time which is a lot of typing.

Is it possible to add new functions to the “res” object, to enable something like this:

res.jsonSuccess( users );

and:

res.jsonFail( users );

Which would output

res.json({
success: true,
payload: users
});

and:

res.json({
success: false,
payload: users
});

respectively.