Skip to content

Commit

Permalink
Add support for array of paths by Router#use(). Closes #175.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmingoia committed Sep 26, 2015
1 parent 6e24b3a commit 42131a1
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,15 @@ Router.prototype.use = function () {
var middleware = Array.prototype.slice.call(arguments);
var path;

// support array of paths
if (Array.isArray(middleware[0]) && typeof middleware[0][0] === 'string') {
middleware[0].forEach(function (p) {
router.use.apply(router, [p].concat(middleware.slice(1)));
});

return this;
}

if (typeof middleware[0] === 'string') {
path = middleware.shift();
}
Expand Down
40 changes: 40 additions & 0 deletions test/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,46 @@ describe('Router', function() {
done();
});
});

it('assigns middleware to array of paths', function (done) {
var app = koa();
var router = new Router();

router.use(['/foo', '/bar'], function *(next) {
this.foo = 'foo';
this.bar = 'bar';
yield next;
});

router.get('/foo', function *(next) {
this.body = {
foobar: this.foo + 'bar'
};
});

router.get('/bar', function *(next) {
this.body = {
foobar: 'foo' + this.bar
};
});

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

describe('Router#register()', function() {
Expand Down

0 comments on commit 42131a1

Please sign in to comment.