Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow param middleware to access param name #133

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
30 changes: 29 additions & 1 deletion test/lib/layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand All @@ -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();
});
});
Expand Down Expand Up @@ -269,4 +297,4 @@ describe('Layer', function() {
prefix.path.should.equal(false)
});
});
});
});