diff --git a/README.md b/README.md index bfcdd87..8e48bca 100644 --- a/README.md +++ b/README.md @@ -9,4 +9,5 @@ - [x] 数据库 - [ ] 缓存 - [ ] 界面 - - [ ] 定时任务 \ No newline at end of file + - [ ] 定时任务 + - [ ] htmx \ No newline at end of file diff --git a/src/middlewares/install.js b/src/middlewares/install.js index 0db2696..0472e90 100644 --- a/src/middlewares/install.js +++ b/src/middlewares/install.js @@ -15,9 +15,15 @@ export default app => { app.use( auth({ whiteList: [ - { pattern: "/", auth: "try" }, - "/api/login", - "/api/register" + // API接口访问 + "/api/login", + "/api/register", + { pattern: "/api/v1/status", auth: "try" }, + { pattern: "/api/**/*", auth: true }, + // 静态资源访问 + "", + "/", + "/**/*", ], blackList: [], }) diff --git a/src/utils/router.js b/src/utils/router.js index 46a3f16..1cabd04 100644 --- a/src/utils/router.js +++ b/src/utils/router.js @@ -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 }); } /**