1.1.0 • Published 10 years ago

kroute v1.1.0

Weekly downloads
169
License
MIT
Repository
github
Last release
10 years ago

Kroute

NPM version NPM downloads Build status Test coverage

Modular Koa router middleware with Express-style routes and middleware mounting.

Install

npm install kroute --save

Usage

Kroute exports a function which can be used to create router instances that work with Koa middleware.

var koa = require('koa')
var kroute = require('kroute')

var app = koa()
var router = kroute()

app.use(router)

Initialization

A router can be initialized with default handlers based on a resourceful routing object.

router({
  use: authorizeUser(),
  index: function* () {},
  create: [function* () {}, function* () {}]
})

Actions are mapped as follows:

GET     /                 ->  index
GET     /new              ->  new
POST    /                 ->  create
GET     /:id              ->  show
GET     /:id/edit         ->  edit
PUT     /:id              ->  update
DELETE  /:id              ->  destroy

The object can also contain a use property which is mounted before any routes.

Routes

Every router instance can used to attach request handlers.

router.get('/user', function* () {})

Omitting the path name will ensure the handler is always executed when the method matches.

router.post(function* () {})

Every route method accepts multiple middleware handlers.

router.delete(authorizeUser(), function* () {})

All Methods

Every router provides a .all method for attaching request handlers to every method.

router.all(function* () {})

It accepts a path and multiple middleware like any other method.

router.all('/', authorizeUser(), function* () {})

Mounting Middleware

Every router comes with the ability to mount middleware and handlers.

var mount = kroute()

router.use('/users', mount)

As long as the middleware follows the Koa generator pattern, it can be mounted.

router.use('/users', function* (next) {
  console.log(this.url) //=> "/123" -> Stripped the route prefix.

  yield next
})

Like other methods, .use also accepts multiple request handlers and an optional path.

router.use(authorizeUser(), function* () {})

Params

Every path can be dynamic and use Express-style parameter notation.

router.get('/:user', function* () {
  console.log(this.params.user) //=> "123"
})

Every match is stored in the params as an object.

router.get('/:foo/:bar', function* () {
  console.log(this.params) //=> { foo: "123", bar: "456" }
})

The route can also be a regular expression.

router.get(/^\/blog\/(\d{4})-(\d{2})-(\d{2})\/?$/i, function* (next) {
  console.log(this.params) // => { 0: '2014', 1: '03', 2: '17' }
})

Chaining

Every method returns it's own instance, so routes can be chained together like Express.

router
  .get('/foo', function* () {})
  .post('/bar', function* () {})

Options

Every method accepts an options object as the last argument.

router.get('/foo', function* () {}, { strict: true, sensitive: true })

License

MIT