使用异步初始化快速中间件

时间:2014-05-25 12:45:04

标签: javascript node.js express

我正在编写一些需要访问数据库的快速中间件。它将作为一个包发布,所以我希望它尽可能自包含。我想知道如何处理与数据库的连接。它是异步的(当然),但它只需要在初始化包时发生一次。这应该发生在哪里?

我在想这样的事情。问题是,在数据库准备好之前,中间件会立即传回。

// App
app.use(myMiddleware({
    db: "<db connection string>"
});

// Middleware
module.exports = function(db) {
    // Open db

    return function(req, res, next) {
        // Middleware stuff
    }
}

1 个答案:

答案 0 :(得分:1)

我建议不要使用这样的单例,依赖注入在这里是一个更好的解决方案,每个应用程序的连接几乎不可扩展。连接池可能是个更好的主意。

那就是说,你可以这样做:

var db = null; // to keep our instance
var asked = false; // to not make several requests that override each other
function openDb(db,ready){
    // if we already have it, we return the instance
    if(db !== null) ready(null,db);
    // if it was already asked by another instance, keep track of it
    // to avoid multiple requests.         
    if(asked) asked.push(ready);
    asked = [];
    openDbCode(db,function(err,result){
        if(err) {
           ready(err,null); // error case
           asked.forEach(function(fn){ fn(err,null); }); // notify waiters of failure
        }
        db = result; // save the reference
        asked.forEach(function(fn){ fn(db,null); }); // notify all waiters
    })
}

此函数有效地等待第一个提问者的数据库,然后调用同一实例上的所有人。请注意,此函数将使用提供的第一个连接字符串。

module.exports = function(db) {
    return function(req, res, next) {
       openDb(db,function(err,db){
           if(err) handleDbOpenErrorLogicHere();
           // middleware stuff, same db available here, call next to continue
        });
    };
}