koa-tree-router
Advanced tools
Comparing version 0.9.0 to 0.10.0
{ | ||
"name": "koa-tree-router", | ||
"version": "0.9.0", | ||
"version": "0.10.0", | ||
"description": "A high performance koa router", | ||
@@ -5,0 +5,0 @@ "main": "router.js", |
@@ -91,2 +91,18 @@ # Koa tree router | ||
#### use(middleware) | ||
You can add middleware that is added to all future routes: | ||
```js | ||
router.use(authMiddleware); | ||
router.get("/foo", (ctx) => { /* your code */ }); | ||
router.get("/bar", (ctx) => { /* your code */ }); | ||
router.get("/baz", (ctx) => { /* your code */ }); | ||
``` | ||
This is equivalent to: | ||
```js | ||
router.get("/foo", authMiddleware, (ctx) => { /* your code */ }); | ||
router.get("/bar", authMiddleware, (ctx) => { /* your code */ }); | ||
router.get("/baz", authMiddleware, (ctx) => { /* your code */ }); | ||
``` | ||
#### routes | ||
@@ -119,2 +135,4 @@ Returns router middleware. | ||
Middleware added with `use()` are also added to the nested routes. | ||
#### ctx.params | ||
@@ -121,0 +139,0 @@ This object contains key-value pairs of named route parameters. |
@@ -11,3 +11,3 @@ const http = require("http"); | ||
*/ | ||
constructor(router, path) { | ||
constructor(router, path, handlers = []) { | ||
if (path[0] !== "/") { | ||
@@ -20,2 +20,3 @@ throw new Error("path must begin with '/' in path '" + path + "'"); | ||
} | ||
this.handlers = [...handlers]; | ||
this.r = router; | ||
@@ -41,5 +42,6 @@ this.p = path; | ||
newGroup(path) { | ||
return new RouteGroup(this.r, this.subpath(path)); | ||
return new RouteGroup(this.r, this.subpath(path), this.handlers); | ||
} | ||
on(method, path, ...handle) { | ||
handle.unshift(...this.handlers); | ||
return this.r.on(method, this.subpath(path), ...handle); | ||
@@ -80,2 +82,5 @@ } | ||
} | ||
use(...handle) { | ||
this.handlers.push(...handle); | ||
} | ||
routes() { | ||
@@ -82,0 +87,0 @@ return this.r.routes(); |
@@ -14,2 +14,3 @@ const http = require("http"); | ||
} | ||
this.handlers = []; | ||
this.trees = {}; | ||
@@ -22,2 +23,3 @@ this.opts = opts; | ||
} | ||
handle.unshift(...this.handlers); | ||
if (!this.trees[method]) { | ||
@@ -62,2 +64,5 @@ this.trees[method] = new Node(); | ||
} | ||
use(...handle) { | ||
this.handlers.push(...handle); | ||
} | ||
find(method, path) { | ||
@@ -109,3 +114,3 @@ const tree = this.trees[method]; | ||
newGroup(path) { | ||
return new RouteGroup(this, path); | ||
return new RouteGroup(this, path, this.handlers); | ||
} | ||
@@ -112,0 +117,0 @@ } |
26606
788
186