node package manager
Orgs are free. Discover, share, and reuse code in your team. Create a free org »

koa-path-match

Koa Path Match

NPM version build status Test coverage Dependency Status License Downloads

A simple routing wrapper around path-match. Similar to koa-route, except it optionally handles methods better. All of these routers use path-to-regexp underneath, which is what Express uses as well.

Install v1.x for Koa v1. Install v2.x or next for Koa v2.

const route = require('koa-path-match')({/* options passed to path-to-regexp */})
 
app.use(route('/:id(\\d+)', function * (next) {
  const id = this.params.id
 
  // do stuff 
  switch (this.request.method) {
 
  }
}))

Or you can create middleware per method:

app.use(route('/:id(\\d+)')
  .get(function * () {
    this.body = yield Things.getById(this.params.id)
  })
  .patch(function * () {
    const body = yield require('co-parse').json(this)
    this.body = yield Things.update(this.params.id, body)
  })
  .delete(function * () {
    yield Things.delete(this.params.id)
    this.status = 204
  })
)

API

route(path, fns...)

paths are just like Express routes. fns is either a single middleware or nested arrays of middleware, just like Express.

const router = route(path)

When you don't set fns in the route() function, a router instance is returned.

router[method](fns...)

Define a middleware just for a specific method.

app.use(route('/:id(\\d+)').get(function * () {
  this.body = yield Things.getById(this.params.id)
}))
  • next is not passed as a parameter. I consider this an anti-pattern in Koa - one route/method, one function.

this.params

Any keys defined in the path will be set to this.params, overwriting any already existing keys defined.