npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-path-router

v2.0.1

Published

Radix tree based routing for Koa 2.x

Downloads

90

Readme

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())