Merge pull request #1561 from strongloop/feature/allow-middleware-methods
Allow methods filter for middleware config
This commit is contained in:
commit
9b748cb97f
|
@ -65,6 +65,34 @@ proto.middlewareFromConfig = function(factory, config) {
|
|||
}
|
||||
|
||||
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);
|
||||
|
||||
return this;
|
||||
|
|
|
@ -438,12 +438,29 @@ describe('app', function() {
|
|||
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) {
|
||||
if (err) return done(err);
|
||||
expect(steps).to.eql([
|
||||
['before'],
|
||||
[expectedConfig],
|
||||
['after', 2]
|
||||
['after', 2],
|
||||
[{x: 1}]
|
||||
]);
|
||||
done();
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue