Merge pull request #1561 from strongloop/feature/allow-middleware-methods

Allow methods filter for middleware config
This commit is contained in:
Raymond Feng 2015-08-06 08:23:49 -07:00
commit 9b748cb97f
2 changed files with 46 additions and 1 deletions

View File

@ -65,6 +65,34 @@ proto.middlewareFromConfig = function(factory, config) {
} }
var handler = factory.apply(null, params); var handler = factory.apply(null, params);
// Check if methods/verbs filter exists
var verbs = config.methods || config.verbs;
if (Array.isArray(verbs)) {
verbs = verbs.map(function(verb) {
return verb && verb.toUpperCase();
});
if (verbs.indexOf('ALL') === -1) {
var originalHandler = handler;
if (handler.length <= 3) {
// Regular handler
handler = function(req, res, next) {
if (verbs.indexOf(req.method.toUpperCase()) === -1) {
return next();
}
originalHandler(req, res, next);
};
} else {
// Error handler
handler = function(err, req, res, next) {
if (verbs.indexOf(req.method.toUpperCase()) === -1) {
return next(err);
}
originalHandler(err, req, res, next);
};
}
}
}
this.middleware(config.phase, config.paths || [], handler); this.middleware(config.phase, config.paths || [], handler);
return this; return this;

View File

@ -438,12 +438,29 @@ describe('app', function() {
params: null params: null
}); });
// This should be triggered with matching verbs
app.middlewareFromConfig(handlerFactory, {
enabled: true,
phase: 'routes:before',
methods: ['get', 'head'],
params: {x: 1}
});
// This should be skipped as the verb doesn't match
app.middlewareFromConfig(handlerFactory, {
enabled: true,
phase: 'routes:before',
methods: ['post'],
params: {x: 2}
});
executeMiddlewareHandlers(app, function(err) { executeMiddlewareHandlers(app, function(err) {
if (err) return done(err); if (err) return done(err);
expect(steps).to.eql([ expect(steps).to.eql([
['before'], ['before'],
[expectedConfig], [expectedConfig],
['after', 2] ['after', 2],
[{x: 1}]
]); ]);
done(); done();
}); });