trie-koa-router

1.1.3 • Public • Published

Trie Koa Router

NPM version build status Test coverage

Trie routing for Koa based on routington, a fork of Koa Trie Router.

Features

  • OPTIONS support
  • 405 Method Not Allowed support
  • 501 Not Implemented support

Routes are generally orthogonal, so the order of definition generally doesn't matter. See routington for more details.

Installation

var app = require('koa')()
var Router = require('trie-koa-router')
var router = new Router()
app.use(router.dispatcher())
 
router.route('/').get(function* (next) {
  this.body = 'homepage'
})
 
router.post('/images', function* (next) {
  var image = yield* this.request.buffer('25mb')
})

API

router.assertImplementsMethod()

Checks if the server implements a particular method and throws a 501 error otherwise. This is not middleware, so you would have to use it in your own middleware.

app.use(myCustomErrorHandler)
 
app.use(function* (next) {
  router.assertImplementsMethod().apply(this) // throws otherwise
  yield next
})

app.use(router.dispatcher())

If you do not do app.use(router.dispatcher()) ever, routing will never work.

router.route(paths)[method](middleware...)

paths can be a nested stack of string paths:

router.route('/one', [
  '/two',
  ['/three', '/four']
])

You can then chain [method](middleware...) calls.

router.route('/')
.get(function* (next) {
 
})
.post(function* (next) {
 
})
.patch(function* (next) {
 
})

router[method](paths, middleware...)

Similar to above, but you define paths as the first argument:

router.get([
  '/one',
  '/two'
], function* (next) {
 
})

this.params

this.params will be defined with any matched parameters.

router.get('/user/:name', function* (next) {
  var name = this.params.name
  var user = yield User.get(name)
  yield next
})

Error handling

The middleware throws an error with code MALFORMEDURL when it encounters a malformed path. An application can try/catch this upstream, identify the error by its code, and handle it however the developer chooses in the context of the application- for example, re-throw as a 404.

Path Definitions

For path definitions, see routington.

Usage

In trie-router, routes are orthogonal and strict. Unlike regexp routing, there's no wildcard routing and you can't next to the next matching route.

Readme

Keywords

Package Sidebar

Install

npm i trie-koa-router

Weekly Downloads

1

Version

1.1.3

License

MIT

Last publish

Collaborators

  • theicebear