什么是合作中间件的首选架构?

如果我创build了一个数据库支持的路由中间件来检查一些数据,而我现在想让它传递给一个视图/渲染中间件,那我最好的办法是什么?

我是不是该:

  • 将我提取的数据附加到请求对象,并将我的渲染层设置为链中的下一个?
  • 直接调用渲染层,就像我自己的路由器像中间件一样调用它?
  • 也许还有其他一些build议?

我正在寻找一些通用的架构build议,这可能会帮助我确保我创build的每个function组件都不会变得难以维护和庞大。 我读过的一些东西有利于将事物分解成尽可能多的模块,这使得我认为上面的两个select可能是好的。

但也许一个更好,或者有什么我失踪?

如果您使用快速路线,鼓励重用和简单化的可靠架构如下所示:

 app.use(errorHandler); // errorHandler takes 4 arguments so express calls it with next(err) app.get('/some/route.:format?', checkAssumptions, getData, sendResponse); 

… checkAssumptions,getData和sendResponse只是例子 – 您可以根据应用程序的需要制作更长或更短的路线链。 这些function可能如下所示:

 function checkAssumptions(req, res, next) { if (!req.session.user) return next(new Error('must be logged in')); return next(); } function getData(req, res, next) { someDB.getData(function(err, data) { if (err) return next(err); // now our view template automatically has this data, making this method reusable: res.localData = data; next(); }); } function sendResponse(req, res, next) { // send JSON if the user asked for the JSON version if (req.params.format === 'json') return res.send(res.localData); // otherwise render some HTML res.render('some/template'); }