问题
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 toif (err) return callback(err);to prevent further execution after the callback is called.if (error) return callback(error);is missing right inside themongodb.connect()callback in case there is a connection error.
来源:https://stackoverflow.com/questions/27719918/how-to-register-async-middleware-module-within-express-js-app