Badi8beach
Badi8beach

Reputation: 556

Any way to conditionally skip middleware with next() in express?

So for example-

//Functions

var validationCheck = function(req, res, next){
  if(req.session.userId && req.session.token)
      next('validationCatch') //Is this possible to skip middleware if not needed?
  else
      next()
}

var getUserId = function(req, res, next){
  req.session.userId = DB.getUserId
  next()
}

var getToken = function(req, res, next){
  req.session.token = DB.getToken
  next()
}

//a catcher function to direct to next function depending on route
var validationCatch = function(req, res, next){
  next()
}

//Routes

app.get(api + '/feature1', validationCheck, getUserId, getToken, validationCatch, feature1)
app.get(api + '/feature2', validationCheck, getUserId, getToken, validationCatch, feature2)

My goal is to skip unnecessary middleware if information is already cached from previous routes. So in above example, feature2 doesnt have to enter getUserId and getToken if feature1 has already been called, thus making response faster.

If not possible, please state a more efficient architecture to handle repetitive validation processes. Thanks

Upvotes: 4

Views: 2606

Answers (1)

PatrickD
PatrickD

Reputation: 1156

Instead of register the callbacks directly, just call them in validationCheck if needed. Here is a simple example with getUserId:

var validationCheck = function(req, res, next){
  if(req.session.userId)
      next()
  else {
    getUserId(req, res, function(err){
      next(err)
    })
  }      
}

Upvotes: 5

Related Questions