impress-router
意思是 router in express for koa, 取个谐音 从express 的router 部分抄出来的, 目前少 router.param 这个功能
代码测试覆盖率 93%, 有些实在不想写, 也没ignore 掉~ 地址 https://github.com/magicdawn/impress-router
---------------我是分割线----------------------
impress-router
Express style router for koa
Install
npm i impress-router --save
API
basic
var Router = require('impress-router');
var router = Router();
app.use(router);
new Router(options)
, or with out new Router(options)
Options
- goNext: default true, whether go down stream
- strict,sensitive: these are path-to-regexp options
- mergeParams: default true, whether merge params when nested router
middleware
use middleware on some path, and you got ctx.path
ctx.basePath
ctx.originalPath
just as Express’s req.baseUrl
/ req.originalUrl
does:
var app = require('koa')();
var router = require('impress-router')();
app.use(router);
router.use('/public',function (next){
// when requesting `/public/js/foo.js`
this.path; // `/js/foo.js`
this.basePath; // `/public`
this.originalPath; // `/public/js/foo.js`
yield next;
});
Em, use on all request:
var app = require('koa')();
var router = require('impress-router')();
app.use(router);
router.use(function * (next){
this.user = { name: 'foo', age: 18 };
yield* next;
})
route
Features
GET POST ...
methods exposed bymethods
module are supported- all supported,
router.all(path,fn)
- auto
OPTIONS
response - auto
HEAD
response
var app = require('koa')();
var router = require('impress-router')();
app.use(router);
router.get('/hello',function * (){
this.body = 'hello';
});
router.all('/hello',function * (){
this.body = 'hello';
});
params
var app = require('koa')();
var Router = require('impress-router');
var router = Router();
app.use(router);
var userRouter = Router();
router.use('/user/:uid', userRouter);
userRouter.get('/get_:field', function * () {
this.body = {
uid: this.params.uid,
field: this.params.field
}
});
// GET /user/magicdawn/get_name
// =>
// { uid: 'magicdawn', field: 'name' }
Why
koa-router is not handy as expected, so …
License
MIT © 2015 Magicdawn http://magicdawn.mit-license.org
var router = require('impress-router')();
app.use(router);
这用法是否有点蹩脚?如果把app传进去,会不会更好一点呢?
比如
var router = require('impress-router')(app);
app.use(router) 不是express 的标准做法么~
如果把app传进去,会不会更好一点呢?
把app传进去是为了啥? 省掉 app.use(router)
这一步? 但是router是一个标准的 koa middleware呀, 就是说可以有多个 router, 可以在某一个path上use 一个router
这个问题又回到了这个issue https://github.com/koajs/koa/issues/473 middleware 老实返回 middleware, 不要管别人怎么用你 plugin要求传 app进去, 去extend app/context/request/response