【问题标题】:How to handle mongoose connection delay in node acl如何处理节点 acl 中的猫鼬连接延迟
【发布时间】:2018-12-28 14:36:26
【问题描述】:

我正在为我的 express 应用程序实现 acl usind node_acl。 我在一个单独的文件中建立数据库连接来处理猫鼬的连接时间,如下所示: 连接.js:

const   mongoose = require('mongoose');

module.exports = function initConnection(callback) {
    mongoose.connect('mongodb://127.0.0.1:27017/aclExample', {});
    var db = mongoose.connection;
    db1 = mongoose.connection.db;
    db.on('error', function (err) {
      console.error('Failed to connect to database');
      process.exit(1);
    });

    db.once('open', function () {
      console.info("Connected to database");
      callback(db1);
      console.log('acl is now set');
    });
};

并将其包含在 app.js 中以创建这样的 acl 对象

var node_acl = require('acl');
var connectACL = require('@root/fe-server/middlewares/fe.middleware.acl.js');
connectACL(function(db){
acl = new node_acl(new node_acl.mongodbBackend(db, 'acl_'));
});
console.log('ACL: ',acl);

问题是console.log 在数据库连接建立之前执行。我该如何处理?我必须在我的 app.js 和其他文件中使用 acl 来进行路由授权,因此在回调中使用它总是没有意义。 提前致谢。

【问题讨论】:

    标签: node.js mongodb express acl


    【解决方案1】:

    您可以承诺创建 acl,或将其移至某种初始化层。

      const promise = new Promise(resolve => connectACL(resolve));
      promise.then(db => { 
        return new new node_acl.mongodbBackend(db, 'acl_')
      })
      .then(acl => {
         APP.setAcl(acl);
         APP.bootsrtap()
      })
    
      //or with node 7.8+
      (async (){
            const db = await new Promise(resolve => connectACL(resolve));
            const acl = new node_acl.mongodbBackend(db, 'acl_');
            application.bootstrapOrSomethingLikeThis()
      })()
    

    【讨论】:

    • 什么是APP.setAcl(acl)?我的意思是什么是APP?
    猜你喜欢
    • 2022-01-26
    • 2020-11-10
    • 2019-05-21
    • 2017-01-04
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多