我有一些类似于以下中间件函数:
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'});
}
有没有一种方法将它们封装到一个函数中?这样我就可以像这样做:
function respondIfValid(req, res, next) {
// Evoke the following middleware:
// validate
// checkValid
// respond
}
app.use('/', respondIfValid);
改为:
app.use('/', validate, checkValid, respond);