diff --git a/lib/router.js b/lib/router.js index 1c18098..307c615 100644 --- a/lib/router.js +++ b/lib/router.js @@ -359,7 +359,12 @@ Router.prototype.routes = Router.prototype.middleware = function () { memo.push(function(ctx, next) { ctx.captures = layer.captures(path, ctx.captures); ctx.params = layer.params(path, ctx.captures, ctx.params); + ctx.routerPath = layer.path; ctx.routerName = layer.name; + ctx._matchedRoute = layer.path; + if (layer.name) { + ctx._matchedRouteName = layer.name; + } return next(); }); return memo.concat(layer.stack); @@ -440,7 +445,7 @@ Router.prototype.allowedMethods = function (options) { let notImplementedThrowable = (typeof options.notImplemented === 'function') ? options.notImplemented() // set whatever the user returns from their function : new HttpError.NotImplemented(); - + throw notImplementedThrowable; } else { ctx.status = 501; @@ -453,7 +458,7 @@ Router.prototype.allowedMethods = function (options) { ctx.set('Allow', allowedArr.join(', ')); } else if (!allowed[ctx.method]) { if (options.throw) { - let notAllowedThrowable = (typeof options.methodNotAllowed === 'function') + let notAllowedThrowable = (typeof options.methodNotAllowed === 'function') ? options.methodNotAllowed() // set whatever the user returns from their function : new HttpError.MethodNotAllowed(); diff --git a/test/lib/router.js b/test/lib/router.js index 07d5ab7..ea9334b 100644 --- a/test/lib/router.js +++ b/test/lib/router.js @@ -1674,8 +1674,8 @@ describe('Router', function () { const app = new Koa(); const router = new Router(); const middleware = function (ctx, next) { + next(); expect(ctx._matchedRoute).to.be('/users/:id') - return next(); }; router.use(middleware); @@ -1734,6 +1734,46 @@ describe('Router', function () { done(); }); }); + + it('places a `routerPath` value on the context for current route', function(done) { + const app = new Koa(); + const router = new Router(); + + router.get('/users/:id', function (ctx) { + expect(ctx.routerPath).to.be('/users/:id') + ctx.status = 200 + }); + + request(http.createServer(app.use(router.routes()).callback())) + .get('/users/1') + .expect(200) + .end(function(err, res) { + if (err) return done(err); + done(); + }); + }); + + it('places a `_matchedRoute` value on the context for current route', function(done) { + const app = new Koa(); + const router = new Router(); + + router.get('/users/list', function (ctx) { + expect(ctx._matchedRoute).to.be('/users/list') + ctx.status = 200 + }); + router.get('/users/:id', function (ctx) { + expect(ctx._matchedRoute).to.be('/users/:id') + ctx.status = 200 + }); + + request(http.createServer(app.use(router.routes()).callback())) + .get('/users/list') + .expect(200) + .end(function(err, res) { + if (err) return done(err); + done(); + }); + }); }); describe('If no HEAD method, default to GET', function () {