diff --git a/lib/layer.js b/lib/layer.js index 02724e3..b83c962 100644 --- a/lib/layer.js +++ b/lib/layer.js @@ -177,7 +177,7 @@ Layer.prototype.param = function (param, fn) { const stack = this.stack; const params = this.paramNames; const middleware = function (ctx, next) { - return fn.call(this, ctx.params[param], ctx, next); + return fn.call(middleware, ctx.params[param], ctx, next); }; middleware.param = param; diff --git a/test/lib/layer.js b/test/lib/layer.js index fe1ef24..677a1a0 100644 --- a/test/lib/layer.js +++ b/test/lib/layer.js @@ -175,6 +175,33 @@ describe('Layer', function() { if (!id) return ctx.status = 404; return next(); }); + router.stack.push(route); + app.use(router.middleware()); + request(http.createServer(app.callback())) + .get('/users/3') + .expect(200) + .end(function(err, res) { + if (err) return done(err); + res.should.have.property('body'); + res.body.should.have.property('name', 'alex'); + done(); + }); + }); + + it('composes middleware for generic param fn', function(done) { + const app = new Koa(); + const router = new Router(); + const route = new Layer('/users/:user', ['GET'], [function (ctx) { + ctx.body = ctx.user; + }]); + route.param('user', constructFromParam); + + function constructFromParam (id, ctx, next) { + ctx[this.param] = { name: 'alex', fromParam: this.param} + if (!id) return ctx.status = 404 + return next() + } + router.stack.push(route); app.use(router.middleware()); request(http.createServer(app.callback())) @@ -184,6 +211,7 @@ describe('Layer', function() { if (err) return done(err); res.should.have.property('body'); res.body.should.have.property('name', 'alex'); + res.body.should.have.property('fromParam', 'user'); done(); }); }); @@ -269,4 +297,4 @@ describe('Layer', function() { prefix.path.should.equal(false) }); }); -}); \ No newline at end of file +});