Skip to content

Commit

Permalink
Merge pull request strongloop#1561 from strongloop/feature/allow-midd…
Browse files Browse the repository at this point in the history
…leware-methods

Allow methods filter for middleware config
  • Loading branch information
raymondfeng committed Aug 6, 2015
2 parents 004baad + c44a19d commit 9b748cb
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
28 changes: 28 additions & 0 deletions lib/server-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
19 changes: 18 additions & 1 deletion test/app.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down

0 comments on commit 9b748cb

Please sign in to comment.