Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 531
John Avatar asked Mar 03 '16 20:03

John


People also ask

What does res JSON () do in Express?

json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.

How do I increase my Express timeout?

Simply put, you need to configure the timeout value on the HTTP Server that express generates when you call the listen method. For example: // create an express app const app = express(); // add a route that delays response for 3 minutes app. get('/test', (req, res) => { setTimeout(() => { res.

What is Req Res next in Nodejs?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

What is return next (); in Express?

app. use((req, res, next) => { //next() or return next() }); In the function app. use((req, res, next), we have three callbacks i.e. request, response and next. So, if you want to use next() then simply write next() and if you want to use return next then simply write return next().


2 Answers

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"]);
});
like image 88
chrisbajorin Avatar answered Sep 23 '22 12:09

chrisbajorin


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)
    })
})
like image 42
Aminadav Glickshtein Avatar answered Sep 19 '22 12:09

Aminadav Glickshtein