koa-express-router
Express's Router adapted for Koa v2.x
- Express-style routing using
router.use
,router.all
,router.METHOD
,router.param
etc - Support router prefix
- Support query matching
Thanks To
- Express. This repo is based on the codes on expressjs/express
- path-to-regexp
Installation
npm install koa-express-router
Usage
Basics
Just like express
Differences
- use
new
to create instances - use
.routes()
or.routes(false)
to export a router
const Koa = ;const Router = ; // change default settingsRouterdefaultOptionsmergeParams = true; // define sub router with an optional prefix// NOTE: different from Express: use new to create instancesconst subRtr = prefix: '/sub' ; subRtr; subRtr allasync { if /* some condition */false return ; // possible to skip the current route (goto #1) ctxbody += '/sub/list all 1\n'; return ; } ; subRtrall'/list' async { // #1 // the logic would come here ctxbody += '/sub/list all 2\n';}; // define top router without a prefixconst topRtr = ;topRtr;topRtr; // NOTE: different from Express: use .routes() to export// no need to pass arguments to .routes()// if .routes() is to be used by a Router from 'koa-express-router'topRtr; const app = ;// pass 'false' when .routes() may be used// by app.use, compose, or something other than a Router from 'koa-express-router'app;app;
Output
- GET /
global use
- PATCH /top/10/sub/ (does not match any path in subRtr)
global use /top/:someID someID => 10 /sub use
- GET /top/bad/sub/list (does not match the use for subRtr.routes())
global use
- GET /top/2/sub/list
global use /top/:someID someID => 2 /sub use /sub/list all 1 /sub/list get
- PUT /top/3/sub/list
global use /top/:someID someID => 3 /sub use /sub/list all 1 /sub/list all 2
Query Matching
Note: this feature is only designed for simple matching. If the matching condition becomes complex, it is recommended that the user consider return next('route')
for better readability. See below.
// use an object for query matching schema// the value part can be a primitiverouter; router // the value part can be a function // the value part can be a regexp // the value part can be a string array (meaning or) ; // complex query condition examplerouter; router;
Caveats
- Not ready for production use
Not support other less common HTTP methods- Not benchmarked
License
MIT