Skip to content

Commit

Permalink
Fix #182.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmingoia committed Oct 2, 2015
1 parent c8b4879 commit e486a93
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ Router.prototype.routes = Router.prototype.middleware = function () {

if (matched.pathAndMethod.length) {
i = matched.pathAndMethod.length;
while (i--) {
while (matched.route && i--) {
layer = matched.pathAndMethod[i];
ii = layer.stack.length;
this.captures = layer.captures(path, this.captures);
Expand Down Expand Up @@ -589,7 +589,8 @@ Router.prototype.match = function (path, method) {
var layer;
var matched = {
path: [],
pathAndMethod: []
pathAndMethod: [],
route: false
};

for (var len = layers.length, i = 0; i < len; i++) {
Expand All @@ -600,8 +601,9 @@ Router.prototype.match = function (path, method) {
if (layer.match(path)) {
matched.path.push(layer);

if (!layer.methods.length || ~layer.methods.indexOf(method)) {
if (layer.methods.length === 0 || ~layer.methods.indexOf(method)) {
matched.pathAndMethod.push(layer);
if (layer.methods.length) matched.route = true;
}
}
}
Expand Down
27 changes: 27 additions & 0 deletions test/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,33 @@ describe('Router', function() {
});
});

it('matches middleware only if route was matched (gh-182)', function (done) {
var app = koa();
var router = new Router();
var otherRouter = new Router();

router.use(function *(next) {
this.body = { bar: 'baz' };
yield next;
});

otherRouter.get('/bar', function *(next) {
this.body = this.body || { foo: 'bar' };
});

app.use(router.routes()).use(otherRouter.routes());

request(http.createServer(app.callback()))
.get('/bar')
.expect(200)
.end(function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('foo', 'bar');
expect(res.body).to.not.have.property('bar');
done();
})
});

it('matches first to last', function (done) {
var app = koa();
var router = new Router();
Expand Down

0 comments on commit e486a93

Please sign in to comment.