e-MEE
e-MEE

Reputation: 508

ExpressJS branching routes based on request parameters

I have 4 middleware functions: a, b, c, d.

If the body contains a value X, I want to execute a then b, else I want to execute c then d.

My code looks like this:

app.post('/', (req, res, next) => {
  if (req.body.X) {
    next();
  } else {
    next('route');
    return;
  }
}, a, b);

app.post('/', c, d);

Is there a more elegant way for this? Is there a way (or package) that makes these kind of routers more readable?

Upvotes: 0

Views: 147

Answers (1)

Jose Hermosilla Rodrigo
Jose Hermosilla Rodrigo

Reputation: 3683

I think you don't need to have two routes for this. You can check for req.body.X in middlewares a and b.

// Middlewares a and b
module.exports = function(req, res, next){
  if(req.body.X){/* Do stuff */} // if is the middleware "a" call next()
                                 // else, is "b" finish with a response i.e. res.send()
  else next();
}

// Middlewares c and d
module.exports = function(){
  // Do whatever, if middleware "c" call next() else finish with a response
}

// Route 
app.post('/', a, b, c, d);

Upvotes: 1

Related Questions