高速ルートを使用している場合、再利用と簡素化を促進する信頼性の高いアーキテクチャは次のようになります。
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 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');
}