Snymax
Snymax

Reputation: 357

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

Upvotes: 7

Views: 2843

Answers (3)

Clark DNcom
Clark DNcom

Reputation: 1

typeof next != 'undefined' will always be True. So answer is not good.

first you need to use '!==' because yu compare the type.

i guess next its a promise or something , so youll always get something if you try to get the type from it

Upvotes: 0

Anurag Kumar
Anurag Kumar

Reputation: 1489

Snymax You can check in the function if next is defined or not. If defined you can call next and if not do what you want.

WORKED FOR ME.

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

I hope it helps.

Thank You

Upvotes: 0

Snymax
Snymax

Reputation: 357

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));

Upvotes: 3

Related Questions