user1037355
user1037355

Reputation:

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.

Upvotes: 8

Views: 3679

Answers (3)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

Sometimes I want to extend current method with new method. For example, log everything that I sent.

This what you can do:

app.use(function (req, res, next) {
    var _send = res.send
    res.send = function (data) {
      console.log('log method on data', data)
      // Call Original function
      _send.apply(res, arguments)
    })
})

Upvotes: 2

chrisbajorin
chrisbajorin

Reputation: 6153

As loadaverage pointed out, middleware is how you do it. For some more specificity:

app.use(function(req, res, next) {

    res.jsonFail = function(users) {
        return res.json({
            success: false,
            payload: users
        })
    };

    res.jsonSuccess = function(users) {
        return res.json({
            success: true,
            payload: users
        });
    };

    next();
});

and then this should work:

app.get("/my/route", function(req, res) {
    return res.jsonSuccess(["you", "me"]);
});

Upvotes: 12

loadaverage
loadaverage

Reputation: 1035

Sure, you can write some simple middleware, then app.use(yourmiddleware) just like usually.

Upvotes: 0

Related Questions