4

I would like to know how to choose between two different middleware functions, depending on the request for the endpoint. It could look something like this:

router.post("/findAvailableAgents", middleware1 || middleware2, (req, res) => {
  // endpoint body
})
Niels Abildgaard
  • 2,662
  • 3
  • 24
  • 32
Dave Kalu
  • 1,520
  • 3
  • 19
  • 38

3 Answers3

6

You could use another middleware which decides whether to choose middleware1 or middleware2

const decideMiddleware = (req, res, next) => {
    if(condition) {
        return middleware1(req, res,next)
    } else {
        return middleware2(req, res,next)
    }
}

And use it in your code

router.post("/findAvailableAgents", decideMiddleware, (req, res))
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Waseem
  • 111
  • 2
2

There is two ways of achieve optional middleware behaviour:

1) Create another middleware, that checks condition and then passes all the parameters into the desired middleware. Example:

const middlewareStrategy = (req,res,next) => {
    if(req.body.token1){
        return middleware1(req,res,next);
    }
    return middleware2(req,res,next);
};

router.post("/findAvailableAgents", middlewareStrategy, handler);

2) Make middleware logic execution in a condition-driven manner. Example:

const middleware1 = (req,res,next) => {
    if(req.body.token){
        // execute some logic, then
        return next();
    }
    // skip this middleware
    next();
};

router.post("/findAvailableAgents", middleware1, middleware2, handler);
ykit9
  • 483
  • 4
  • 7
0

Now you can add multiple middleware using a below peice of code

app.get('/',[middleware.requireAuthentication,middleware.logger], function(req, res){
    res.send('Hello!');
});
Prasanta Bose
  • 674
  • 5
  • 13
  • It's not working. Perhaps I should be clearer with my question. I need to use either middlewares to process requests. – Dave Kalu Sep 13 '18 at 14:38
  • Here's the idea. app.get('/',middleware1,middleware2, function(req, res){ res.send('Hello!'); }); We have two middlewares. Now, pass the result from middleware 1 to middleware 2. Refernce : https://stackoverflow.com/questions/18875292/passing-variables-to-the-next-middleware-using-next-in-express-js @DaveKalu – Prasanta Bose Sep 13 '18 at 14:42
  • No, I don't need to pass the request to the next middleware. I need to reject or resolve the request if the request is valid. That is why I thought an "or" operator would work. – Dave Kalu Sep 13 '18 at 14:59