如果我制作了一些可以协同工作的中间件,那么分组和管理功能的最佳约定是什么?
在我的
server.js
文件中,我目前刚刚通过 app.use
调用将它们逐一列出。
然而,我突然想到,如果我的集合中的第一个不产生任何数据,则可以跳过该组中的后续数据。我想这最终是一个聚合,尽管我在其他项目中没有看到任何这样的例子。
connect中间件对于此类问题有一个很好的例子。看看bodyParser:
app.use(connect.bodyParser()); // use your own grouping here
相当于
app.use(connect.json());
app.use(connect.urlencoded());
app.use(connect.multipart());
在内部,
bodyParser
函数只是通过前面提到的每个中间件函数传递
req
和
res
对象
exports = module.exports = function bodyParser(options){
var _urlencoded = urlencoded(options)
, _multipart = multipart(options)
, _json = json(options);
return function bodyParser(req, res, next) {
_json(req, res, function(err){
if (err) return next(err);
_urlencoded(req, res, function(err){
if (err) return next(err);
_multipart(req, res, next);
});
});
}
};
完整代码可以在 github
编辑
在下面的评论中得知,传递数组将实现完全相同的效果,因此不需要额外的模块。 :-)
我确信已经有更全面的东西了,但我最终做到了:
/**
* Macro method to group together middleware.
*/
function macro (...middlewares) {
// list of middlewares is passed in and a new one is returned
return (req, res, next) => {
// express objects are locked in this scope and then
// _innerMacro calls itself with access to them
let index = 0;
(function _innerMacro() {
// methods are called in order and passes itself in as next
if(index < middlewares.length){
middlewares[index++](req, res, _innerMacro)
} else {
// finally, next is called
next();
}
})();
}
}
然后像这样使用它:
var macro = macro(
middleware1,
middleware2,
middleware3
);
app.post('/rout', macro);