mongodb からのイベントを処理するパッケージ (またはパターン) を探しているので、ネストされたコールバックを回避し、mongodb ロジックを要求ハンドラーから除外できます。
現在、次のようなコードがあります。
start-express.js (サーバー)
var express = require('express');
var Resource = require('express-resource');
var app = express.createServer();
// create express-resource handler which essentially does app.get('things', ...)
var things = app.resource('things', require('./things.js'));
app.listen(port);
things.js (エクスプレス リソースリクエスト ハンドラー)
require('./things-provider');
// handle request 'http://example.com/things'
exports.index = function(request, response) {
sendThings(db, response);
};
things-provider.js (mongodb クエリを処理します)
var mongodb = require('mongodb')
// create database connection
var server = new mongodb.Server(host, port, {auto_reconnect: true});
var db = new mongodb.Db(dbName, server);
db.open(function (err, db) {
if (err) { }
// auto_reconnect will reopen connection when needed
});
function sendThings(db, response) {
db.collection('things', function(err, collection) {
collection.find(function(err, cursor) {
cursor.toArray(function(err, things) {
response.send(things);
});
});
});
}
module.exports.sendThings = sendThings;
http 応答オブジェクトをデータベース ハンドラーに渡したり、(さらに悪いことに) http 応答ハンドラーで db 要求を処理したりしたくありません。
最近、私がやりたいことは、http 要求/応答を登録し、http 応答を処理して送信する前にデータベースからの応答 (イベント) を待機するイベント ハンドラーを作成することであることに気付きました。
これは、node.js が既に行っていることと重複しているように思えます。このユースケースを処理する既存のフレームワークはありますか?