koa-path-router

2.0.1 • Public • Published

koa-path-router

Build Status Coverage Status

Fast and simple routing for koa. radix-router is used to achieve fast and consistent lookups.

Installation

npm i --save koa-path-router

Usage

A minimal example

const Koa = require('koa')
const app = new Koa()
 
const Router = require('koa-path-router')
const router = new Router({
  // define middleware for all routes (optional)
  middleware: [
    async (ctx, next) => {
      const startTime = Date.now()
      await next()
      console.log(`Request took ${Date.now() - startTime} ms`)
    }
  ]
})
 
// add routes via the register function
router.register({
  path: '/hello',
  method: 'GET',
  handler: async (ctx) => {
    ctx.body = 'Hello world'
  }
})
 
app.use(router.getRequestHandler())
 
app.listen(8080, () => {
  console.log('Server is listening on port 8080')
})

Creating an instance of the router

const Router = require('koa-path-router')
 
const router = new Router()

Middleware for all routes handled by the router can be passed into the constructor

const router = new Router({
  // define middleware for all routes (optional)
  middleware: [
    async (ctx, next) => {
      const startTime = Date.now()
      await next()
      console.log(`Request took ${Date.now() - startTime} ms`)
    }
  ]
})

Adding more middleware

Additional middleware can be added to subsequent routes via use:

router.use(async (ctx, next) => {
  console.log('another layer of middleware')
  return next()
})

Multiple functions can be passed in if needed:

router.use(...middlewareFuncs)
 
// or
router.use(functionA, functionB)

Registering routes

Routes can be added by using the register function:

// add routes via the register function
router.register({
  path: '/some/path',
  method: 'POST',
  // route specific middleware (optional)
  middleware: [
    async (ctx, next) => {
      const startTime = Date.now()
      await next()
      console.log(Date.now() - startTime)
    }
  ]
  handler: async (ctx) => {
    ctx.body = 'Hello world'
  }
})

You can grab querystring values from the ctx.request object (as usual).

router.register({
  path: '/some/route',
  method: 'GET',
  handler: async (ctx) => {
    const { query } = ctx.request
    // a request to '/some/route?key=value'
    // will set query to { key: 'value' }
    ctx.body = `Hello world`
  }
})

Placeholders are added by specifying a segment with a colon (:). These values are placed on the ctx.request object:

router.register({
  path: '/some/:placeholder',
  method: 'GET',
  handler: async (ctx) => {
    const { placeholder } = ctx.request.params
    ctx.body = `Hello ${placeholder}`
  }
})
 

Wildcard routes can be added by appending a /** to the end of a route:

router.register({
  path: '/wild/**',
  method: 'GET',
  handler: async (ctx) => {
    // any requests to urls such as '/wild/card' or '/wild/path/not/defined/'
    // will be routed here
    ctx.body = 'wild!'
  }
})

Express style functions are exposed for convenience:

router.get('/another/path', async (ctx) => {
  ctx.body = 'Hello world'
})
 
router.post('/some/other/path', async (ctx) => {
  ctx.body = 'Hello world again'
})

Multiple middleware functions can be passed in before the final handler as well:

router.post('/a/path',
  // middleware A
  async (ctx, next) => {
    next()
  },
 
  // middleware B
  async (ctx, next) => {
    next()
  },
 
  // more middleware can be added here..
  // (middleware C, middleware D, etc.)
 
  // last function is the final request handler
  async (ctx) => {
    ctx.body = 'hi'
  })
 
// alternatively if you have a your middleware defined in an array, you can do
router.post('path', ...middleware, finalHandler)

To use the router with a koa app instance, pass it the function returned by getRequestHandler:

app.use(router.getRequestHandler())

Package Sidebar

Install

npm i koa-path-router

Weekly Downloads

39

Version

2.0.1

License

MIT

Last publish

Collaborators

  • charlieduong94