Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if there is a next() function express

is there a way to see if there is a function after the current middleware. ie

router.get('/', function(req, res, next){
    if(next){//always returns true
    }
});

I have a function to fetch the information and depending on the route that information will either be displayed in a table or a form or it will be combined with other data.

I wanted to have a function similar to

function findAll(req, res, next){
    db.findAll(function(err, docs){
        if(next){
            req.list = docs
            return next();
        }else{
            res.render('table', {list:docs};
        }
    });
}

that way I could use the same function in either

router.get('/', findAll, handleData);

or

router.get('/', findAll);

and in either case a response will be sent. is there a way i can define the stack for the router like express does in the next() handler

example

var layer = stack[idx++];

this catches the next function if it exists but I cannot access this scope from my function. is there a way i can define the layers myself.

This seems like it could be very usefull in preventing redundant code

like image 363
Snymax Avatar asked Dec 09 '14 13:12

Snymax


1 Answers

thanks to paul i was able to work around the next issue kind of. currently this working

function findAll(callback){
    return function send(req, res){
        db.findAll(function(err, docs){
            if(callback){
                req.docs = docs
                return callback(req, res, next());
            }
            res.render('table', {docs:docs});
        });
    }
}
function handleData(req, res, next){
    res.send(req.docs);
}

will work with

router.get('/', findAll());

or

router.get('/', findAll(handleData));
like image 88
Snymax Avatar answered Oct 06 '22 13:10

Snymax