From 73c38d426c2604a230fc1bcfae5ab7d8a4db11b9 Mon Sep 17 00:00:00 2001 From: Alex Mingoia Date: Sat, 26 Sep 2015 14:29:06 -0700 Subject: [PATCH] Inherit param middleware when nesting routers. Fixes #170. --- lib/router.js | 6 ++++++ test/lib/router.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/router.js b/lib/router.js index 327d8e5..5a90f5a 100644 --- a/lib/router.js +++ b/lib/router.js @@ -255,6 +255,12 @@ Router.prototype.use = function () { router.stack.push(layer); }); + if (router.params) { + Object.keys(router.params).forEach(function (key) { + fn.router.param(key, router.params[key]); + }); + } + return false; } diff --git a/test/lib/router.js b/test/lib/router.js index 36ffa5c..23c594e 100644 --- a/test/lib/router.js +++ b/test/lib/router.js @@ -641,6 +641,36 @@ describe('Router', function() { done(); }); }); + + it('runs parent parameter middleware for subrouter', function (done) { + var app = koa(); + var router = new Router(); + var subrouter = new Router(); + subrouter.get('/:cid', function *(next) { + this.body = { + id: this.params.id, + cid: this.params.cid + }; + }); + router + .param('id', function *(id, next) { + this.params.id = 'ran'; + if (!id) return this.status = 404; + yield next; + }) + .use('/:id/children', subrouter.routes()); + + request(http.createServer(app.use(router.routes()).callback())) + .get('/did-not-run/children/2') + .expect(200) + .end(function(err, res) { + if (err) return done(err); + res.should.have.property('body'); + res.body.should.have.property('id', 'ran'); + res.body.should.have.property('cid', '2'); + done(); + }); + }); }); describe('Router#opts', function() {