How to register async middleware module within express.js app?

家住魔仙堡 提交于 2019-12-13 04:15:53

问题


I'm working on an express app that uses the node_acl module with a MongoDB backend. I made a module that creates an instance of node_acl and configures it asynchronously. This middleware should be called as the second middleware on the stack to control request access.

// myModule.js

exports.init = function(callback) {
mongodb.connect("mongodb://localhost:27017/mydb", function(error, db) {
    var mongoBackend = new acl.mongodbBackend(db, 'acl_');
    acl = new acl(mongoBackend);    
    // Defining roles for acl 

    ....

    acl.addRoleParents('..', '..', function(err){
        if (err) callback(err, acl);
        acl.addRoleParents('..', '..', function(err){
            if (err) callback(err, acl);
            acl.addRoleParents('..', ['..','..'], function(err){
                if (err) {
                    callback(err, acl);
                } else {
                    callback(null, acl);
                };
            });
        });
    });
}); 
};

How can I register this module to be the second middleware of the stack? Do I need to edit myModule.js in some way?

Thank you guys


回答1:


That module already provides an Express middleware, so it's as simple as:

// ...
var myModule = require('./myModule');

myModule.init(function(err, acl) {
  if (err) throw err;

  // insert first `app.use()` here

  app.use(acl.middleware());

  // insert other middleware/route handlers here
});

Although I should note a couple of things with your existing code:

  • if (err) callback(err, acl); should be changed to if (err) return callback(err); to prevent further execution after the callback is called.

  • if (error) return callback(error); is missing right inside the mongodb.connect() callback in case there is a connection error.



来源:https://stackoverflow.com/questions/27719918/how-to-register-async-middleware-module-within-express-js-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!