diff --git a/lib/server-app.js b/lib/server-app.js index 7e51dc91..237a6254 100644 --- a/lib/server-app.js +++ b/lib/server-app.js @@ -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; diff --git a/test/app.test.js b/test/app.test.js index 47988ff6..2701ef9d 100644 --- a/test/app.test.js +++ b/test/app.test.js @@ -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(); });