Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap multiple middleware functions into one?

I have a number of middleware functions similar to the following:

function validate(req, res, next) {
  req.validationError = new Error('invalid');
}

function checkValid(req, res, next) {
  if (req.validationError) {
    next(req.validationError);
  } else {
    next();
  }
}

function respond() {
  res.json({result: 'success'});
}

Is there a way to wrap them into one function? So I'd do something like:

function respondIfValid(req, res, next) {
  // Evoke the following middleware: 

  // validate
  // checkValid
  // respond
}

app.use('/', respondIfValid);

Instead of:

app.use('/', validate, checkValid, respond);
like image 640
sabof Avatar asked Apr 07 '15 12:04

sabof


1 Answers

try with following code

app.use('/', [validate, checkValid,respond]);

OR

var middleware = [validate, checkValid,respond];

app.use('/', middleware );

Need to placed all function in that series as your requirement of execution.

Thanks

like image 117
Dineshaws Avatar answered Oct 22 '22 15:10

Dineshaws