koa-path-match

koa route middleware

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
koa-path-match
3473.0.04 years ago10 years agoMinified + gzip package size for koa-path-match in KB

Readme

Koa Path Match
!NPM versionnpm-imagenpm-url Node.js CI !Test coveragecodecov-imagecodecov-url !Licenselicense-imagelicense-url !Downloadsdownloads-imagedownloads-url
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.
const route = require('koa-path-match')({/* options passed to path-to-regexp */})

app.use(route('/:id(\\d+)', (ctx, next) => {
  const id = ctx.params.id

  // do stuff
  switch (ctx.request.method) {

  }
}))

Or you can create middleware per method:
app.use(route('/:id(\\d+)')
  .get(async ctx => {
    ctx.body = await Things.getById(ctx.params.id)
  })
  .delete(async ctx => {
    await Things.delete(ctx.params.id)
    ctx.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(async ctx => {
  ctx.body = await Things.getById(ctx.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 ctx.params, overwriting any already existing keys defined.