From a6e21027961aabcf580f971e072df25a6f1e1749 Mon Sep 17 00:00:00 2001 From: tunnckoCore Date: Fri, 14 Oct 2016 19:37:47 +0300 Subject: [PATCH] fix(REST): respect routes order in REST APIs --- index.js | 17 ++++++++++++----- test.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 76e907c..e6bee7b 100644 --- a/index.js +++ b/index.js @@ -279,22 +279,29 @@ KoaBetterRouter.prototype.middleware = function middleware (opts) { route.match = this.route(prefixed) } - let params = route.match(ctx.path, ctx.params) - if (!params) { + // - if there's a match and no params it will be empty object! + // - if there are some params they will be here + // - if path not match it will be boolean `false` + let match = route.match(ctx.path, ctx.params) + if (!match) { continue } - route.params = params + route.params = match route.middlewares = route.middlewares.map((fn) => { return utils.isGenerator(fn) ? utils.convert(fn) : fn }) // may be useful for the user ctx.route = route - ctx.params = params + ctx.params = route.params - utils.compose(route.middlewares)(ctx) + // calls next middleware on success + // returns rejected promises on error + return utils.compose(route.middlewares)(ctx).then(() => next()) } + // called when request path not found on routes + // ensure calling next middleware which is after the router return next() } } diff --git a/test.js b/test.js index 65460e2..8b93ef0 100644 --- a/test.js +++ b/test.js @@ -153,3 +153,38 @@ test('should call next middleware correctly', function (done) { done() }) }) + +test('should respect routes defined order (useful on REST APIs)', function (done) { + let api = Router({ prefix: '/api' }).loadMethods() + let app = new Koa() + let called = 0 + + api.get('/profiles/new', function (ctx, next) { + ctx.body = `Create new profile. Route path: ${ctx.route.path}` + return next() + }) + api.get('/profiles/:profile', function (ctx, next) { + ctx.body = `Profile: ${ctx.params.profile}` + return next() + }) + + app.use(api.middleware()) + app.use(function (ctx, next) { + called++ + return next() + }) + + request(app.callback()).get('/api/profiles/new').expect(200, /Create new profile/) + .end(function (err) { + test.ifError(err) + test.strictEqual(called, 1) + + // request specific user profile + request(app.callback()).get('/api/profiles/123').expect(200, /Profile: 123/) + .end(function (err) { + test.ifError(err) + test.strictEqual(called, 2) + done() + }) + }) +})