1

一部のデータをチェックするデータベース バックアップ ルーティング ミドルウェアを作成し、それをビュー/レンダリング ミドルウェアに渡すようにしたい場合、どのような方法が最適ですか?

するべきか:

  • 取得したデータをリクエスト オブジェクトにアタッチし、レンダリング レイヤーをチェーンの次のレイヤーとしてセットアップしますか?
  • 自分のルーターがミドルウェアのように呼び出しているかのように、レンダリング レイヤーを直接呼び出しますか?
  • おそらく他の提案ですか?

私が作成する機能の各コンポーネントが保守不能で大きくならないようにするための一般的なアーキテクチャのアドバイスを探しています。私が読んだいくつかの記事では、物事をできるだけ多くのモジュールに分割することを支持していました。

しかし、おそらく1つの方が優れているか、何か足りないものがありますか?

4

1 に答える 1

2

高速ルートを使用している場合、再利用と簡素化を促進する信頼性の高いアーキテクチャは次のようになります。

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');
}
于 2013-01-10T07:12:10.950 に答える