7

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);
2
  • Is this goal for this middleware to be an atomic unit? Or another way of asking, what's wrong with just putting all the logic in one function? Commented Apr 8, 2015 at 1:57
  • I'm generally curious whether middleware can be used in the above way. Commented Apr 8, 2015 at 11:31

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ideally middleware would be a function.
You can wrap up all function without taking in an array. so we can pass directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.