5

如果我制作了一些可以协同工作的中间件,那么分组和管理功能的最佳约定是什么?

在我的server.js档案中,我目前只是让他们一个接一个地列出app.use来电。

然而,我突然想到,如果我的集合中的第一个没有产生任何数据,那么该组中的后续数据可以跳过。我想这最终是一个聚合,尽管我在其他项目中没有看到任何这样的例子。

4

2 回答 2

1

连接中间件有一个很好的例子来解决这类问题。看一下bodyParser

app.use(connect.bodyParser());  // use your own grouping here

相当于

app.use(connect.json());
app.use(connect.urlencoded());
app.use(connect.multipart());

在内部,该bodyParser函数只是将reqandres对象传递给前面提到的每个中间件函数

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 repo中找到

于 2013-01-14T17:48:59.950 回答
0

编辑

在下面的评论中得知,传递一个数组将获得完全相同的东西,因此不需要额外的模块。:-)


我也在寻找一种方法来做到这一点,因为我的应用程序非常精细,但我不想像其他答案那样嵌套所有内容。

我敢肯定那里已经有更全面的东西,但我最终做到了:

 /**
 * 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);
于 2017-09-27T12:16:19.813 回答