javascript - 具有异步初始化的 Express 中间件

标签 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
    }
}

最佳答案

我建议不要使用这样的单例,依赖注入(inject)是一个更好的解决方案,而且每个应用程序的连接很难扩展。连接池可能是更好的主意。

也就是说,您可以执行以下操作:

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
        });
    };
}

关于javascript - 具有异步初始化的 Express 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23855420/

相关文章:

javascript - 固定在 window 上的位置

javascript - 表单验证和提交

node.js - hapi中使用相对路径访问静态文件

performance - 测量 js 执行时间是否可以判断应用程序响应请求的速度?

javascript - Node 需要绝对路径

javascript - RemoveEventListener 在 Firefox 版本 58 中不起作用

javascript - 尝试将 ng-repeat 从 img 元素移动到父 div

javascript - Express.js发布请求 "Origin null is not allowed"错误

database - 我的服务器使用 node.js,需要设置用户帐户,我应该使用哪个数据库程序?

javascript - 使用 MomentJS 的 Javascript 中的无效日期