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 handlerthis equal 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,
ctx
will have some extra prop attached
ctx.basePath
the mount pathctx.path
the path withctx.basePath
trimedctx.originalPath
the untrimed pathIt's kind like Express
req.baseUrl
/req.originalUrl
does
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.path
will be/js/foo.js
ctx.basePath
will be/public
ctx.originalPath
will be/public/js/foo.js
router.method(path, handler)
get
/post
/...
methods exposed bymethods
module are supportedall
method supported, viarouter.all(path,fn)
- auto
OPTIONS
response, the router automatic build theAllow
response - auto
HEAD
response
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.use
lack support ofpath
- add
app.get
/app.post
support
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