Skip to content

Commit

Permalink
fix(REST): respect routes order in REST APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
tunnckoCore committed Oct 14, 2016
1 parent dd97fab commit a6e2102
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
17 changes: 12 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
Expand Down
35 changes: 35 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
})

0 comments on commit a6e2102

Please sign in to comment.