Check if there is a next () express function

Is there a way to see if there is a function after the current middleware. i.e

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

      

I have a function to retrieve information and depending on the route, this information will be displayed in a table or form or will be combined with other data.

I wanted to have a function like

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

      

this way I could use the same function in

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

      

or

router.get('/', findAll);

      

and in any case, the answer will be sent. is there a way i can define a stack for a router like express in the following () handler

Example

var layer = stack[idx++];

      

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

It looks like this can be very useful for avoiding redundant code

+3


source to share


1 answer


thanks to paul I was able to sort out the following question. it is currently 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));

      

+2


source







All Articles