impress-router
express style router for koa v2
Install
npm i impress-router -S
basic usage
const App = require('koa')
const Router = require('impress-router')
const app = new App()
const router = new Router()
app.use(router)
new Router(opts)
opts
| key | type | default | description |
|---|---|---|---|
strict | Boolean | false | when false the trailing / is optional`, see path-to-regexp doc |
sensitive | Boolean | false | when false, case is notsensitive, see path-to-regexp doc |
mergeParams | Boolean | true | when true, merge params when we have nested routers |
useThis | Boolean | true | when true, the handlerthisequal toctx, like koa v1 does |
router.use([path], middleware)
middleware can be mount on path, or on the root path
/
arguments
| name | type | required | default | description |
|---|---|---|---|---|
path | String | false | '/' | the mount path |
middleware | Function / Array<Function> | true | the handler |
in the handler,
ctxwill have some extra prop attached
ctx.basePaththe mount pathctx.paththe path withctx.basePathtrimedctx.originalPaththe untrimed pathIt's kind like Express
req.baseUrl/req.originalUrldoes
for Example
const App = require('koa')
const Router = require('impress-router')
const app = new App()
const router = new Router()
app.use(router)
router.use('/public', (ctx, next) {
// when requesting `/public/js/foo.js`
ctx.path // `/js/foo.js`
ctx.basePath // `/public`
ctx.originalPath // `/public/js/foo.js`
return next()
})
when we request
/public/js/foo.js
ctx.pathwill be/js/foo.jsctx.basePathwill be/publicctx.originalPathwill be/public/js/foo.js
router.method(path, handler)
get/post/...methods exposed bymethodsmodule are supportedallmethod supported, viarouter.all(path,fn)- auto
OPTIONSresponse, the router automatic build theAllowresponse - auto
HEADresponse
Example
const app = new (require('koa'))()
const router = new (require('impress-router'))()
app.use(router)
router.get('/hello', ctx => {
ctx.body = 'world'
})
router.all('/foo', ctx => {
ctx.body = 'bar'
})
ctx.params
const app = new (require('koa'))()
const Router = require('impress-router')
const router = new Router()
app.use(router)
const userRouter = new Router()
router.use('/user/:uid', userRouter)
userRouter.get('/:field', ctx => {
ctx.body = {
uid: ctx.params.uid,
field: ctx.params.field,
}
})
// GET /user/magicdawn/name
// =>
// { uid: 'magicdawn', field: 'name' }
router.augmentApp(app)
this method will augment the koa app instance, will
- add
app.use(path, middleware)support, the originalapp.uselack support ofpath - add
app.get/app.postsupport
Why
- express.Router is very nice
- koa-router package is not very friendly, especially on middleware mount on path
so I'm porting it to koa
Changelog
License
the MIT License http://magicdawn.mit-license.org