Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using optional middleware in Express JS

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
})
like image 390
Dave Kalu Avatar asked Jan 27 '23 11:01

Dave Kalu


1 Answers

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))
like image 182
Waseem Avatar answered Jan 31 '23 05:01

Waseem