Skip to content

Commit

Permalink
99 params request ctx (#100)
Browse files Browse the repository at this point in the history
* url params are part of the request and as such showed be part of the request object of koa (ctx.request.params) not just the ctx (ctx.params)

* resolves: #99 add additional test for subroutes

Co-authored-by: Trevor Pellegrini <trevor@Trevors-MacBook-Pro.local>
  • Loading branch information
TLPcoder and Trevor Pellegrini committed Aug 14, 2020
1 parent 5b6d4ea commit 92200d4
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ Router.prototype.routes = Router.prototype.middleware = function () {
layerChain = matchedLayers.reduce(function(memo, layer) {
memo.push(function(ctx, next) {
ctx.captures = layer.captures(path, ctx.captures);
ctx.params = layer.params(path, ctx.captures, ctx.params);
ctx.params = ctx.request.params = layer.params(path, ctx.captures, ctx.params);
ctx.routerPath = layer.path;
ctx.routerName = layer.name;
ctx._matchedRoute = layer.path;
Expand Down
58 changes: 58 additions & 0 deletions test/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,64 @@ describe('Router', function () {
.expect('GET /users', done);
});

it("parameter added to request in ctx", function (done) {
const app = new Koa();
const router = new Router();
router.get("/echo/:saying", function (ctx) {
try {
expect(ctx.params.saying).eql("helloWorld");
expect(ctx.request.params.saying).eql("helloWorld");
ctx.body = { echo: ctx.params.saying };
} catch(err) {
ctx.status = 500;
ctx.body = err.message;
}
});
app.use(router.routes());
request(http.createServer(app.callback()))
.get("/echo/helloWorld")
.expect(200)
.end(function (err, res) {
if (err) return done(err);
expect(res.body).to.eql({ echo: "helloWorld" });
done();
});
});

it("parameter added to request in ctx with sub router", function (done) {
const app = new Koa();
const router = new Router();
const subrouter = new Router();

router.use(function (ctx, next) {
ctx.foo = 'boo';
return next();
});

subrouter
.get('/:saying', function (ctx) {
try {
expect(ctx.params.saying).eql("helloWorld");
expect(ctx.request.params.saying).eql("helloWorld");
ctx.body = { echo: ctx.params.saying };
} catch(err) {
ctx.status = 500;
ctx.body = err.message;
}
});

router.use('/echo', subrouter.routes());
app.use(router.routes());
request(http.createServer(app.callback()))
.get('/echo/helloWorld')
.expect(200)
.end(function (err, res) {
if (err) return done(err);
expect(res.body).to.eql({ echo: "helloWorld" });
done();
});
});

describe('Router#[verb]()', function () {
it('registers route specific to HTTP verb', function () {
const app = new Koa();
Expand Down

0 comments on commit 92200d4

Please sign in to comment.