KishoreRaju February 2016

NodeJs and ExpressJs Unable to separate the common code which is used in error and respose handling

I'm new to NodeJS and expressJs. I have the following code, which is used to get the list of Users

In the following code I would like to separate the code which is in function(error, response, body) method and reuse in different method

How I can do this? I am using these repeatedly in all the methods so I would like to separate this and reuse in all the places.

router.get('/details/*******/all', function(req, res, next) {
    var cookie = request.cookie("JSESSIONID=" + req.cookies.JSESSIONID);
    jar.setCookie(cookie, LIST_OF_STAFF, function(error, cookie) {});
    request({
        url: LIST_OF_STAFF,
        method: "GET",
        jar: jar,
        headers: headers
    }, function(error, response, body) {
        if (!error && response.statusCode === 400 && !_.isUndefined(body)) {
            res.status(400)
            res.json(body);
        } else
        if (!error && response.statusCode === 401 && !_.isUndefined(body)) {
            res.status(401)
            res.json(body);
        } else
        if (!error && response.statusCode === 200 && !_.isUndefined(body)) {
            res.json(JSON.parse(body));
        } else {
            next(error);
        }
    });
});

Answers


Aminadav February 2016

You can move the function to another place, give it's a name. And then you can reuse it.

This for example how it's can be used:

router.get('/details/*******/all', function(req, res, next) {
    var cookie = request.cookie("JSESSIONID=" + req.cookies.JSESSIONID);
    jar.setCookie(cookie, LIST_OF_STAFF, function(error, cookie) {});
    request({
        url: LIST_OF_STAFF,
        method: "GET",
        jar: jar,
        headers: headers
    }, newFunction.bind(null,res);
});

function newFunction (res,error, response, body) {
        // You can use res (res.write)
        if (!error && response.statusCode === 400 && !_.isUndefined(body)) {
            res.status(400)
            res.json(body);
        } else
        if (!error && response.statusCode === 401 && !_.isUndefined(body)) {
            res.status(401)
            res.json(body);
        } else
        if (!error && response.statusCode === 200 && !_.isUndefined(body)) {
            res.json(JSON.parse(body));
        } else {
            next(error);
        }
    }

Post Status

Asked in February 2016
Viewed 1,913 times
Voted 12
Answered 1 times

Search




Leave an answer