|
|
@ -22,21 +22,35 @@ class Router { |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 注册GET路由 |
|
|
|
* 注册GET路由,支持中间件链 |
|
|
|
* @param {string} path - 路由路径 |
|
|
|
* @param {Function} handler - 处理函数 |
|
|
|
* @param {...Function} handlers - 中间件和处理函数 |
|
|
|
*/ |
|
|
|
get(path, handler) { |
|
|
|
this._registerRoute('get', path, handler); |
|
|
|
get(path, ...handlers) { |
|
|
|
this._registerRoute('get', path, handlers); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 注册POST路由 |
|
|
|
* 注册POST路由,支持中间件链 |
|
|
|
* @param {string} path - 路由路径 |
|
|
|
* @param {Function} handler - 处理函数 |
|
|
|
* @param {...Function} handlers - 中间件和处理函数 |
|
|
|
*/ |
|
|
|
post(path, handler) { |
|
|
|
this._registerRoute('post', path, handler); |
|
|
|
post(path, ...handlers) { |
|
|
|
this._registerRoute('post', path, handlers); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 注册PUT路由,支持中间件链 |
|
|
|
*/ |
|
|
|
put(path, ...handlers) { |
|
|
|
this._registerRoute('put', path, handlers); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 注册DELETE路由,支持中间件链 |
|
|
|
*/ |
|
|
|
delete(path, ...handlers) { |
|
|
|
this._registerRoute('delete', path, handlers); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
@ -63,11 +77,11 @@ class Router { |
|
|
|
const { method, path } = ctx; |
|
|
|
const route = this._matchRoute(method.toLowerCase(), path); |
|
|
|
|
|
|
|
// 组合所有中间件和 handler
|
|
|
|
// 组合全局中间件、路由专属中间件和 handler
|
|
|
|
const middlewares = [...this.middlewares]; |
|
|
|
if (route) { |
|
|
|
ctx.params = route.params; |
|
|
|
middlewares.push(route.handler); |
|
|
|
middlewares.push(...route.handlers); |
|
|
|
} |
|
|
|
|
|
|
|
// 用 koa-compose 组合
|
|
|
@ -77,14 +91,14 @@ class Router { |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 内部路由注册方法 |
|
|
|
* 内部路由注册方法,支持中间件链 |
|
|
|
* @private |
|
|
|
*/ |
|
|
|
_registerRoute(method, path, handler) { |
|
|
|
_registerRoute(method, path, handlers) { |
|
|
|
const fullPath = this.prefix + path; |
|
|
|
const keys = []; |
|
|
|
const matcher = match(fullPath, { decode: decodeURIComponent }); |
|
|
|
this.routes[method].push({ path: fullPath, matcher, keys, handler }); |
|
|
|
this.routes[method].push({ path: fullPath, matcher, keys, handlers }); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|