Browse Source

feat: 更新文档和路由中间件,支持中间件链

alpha
谢亚昕 2 months ago
parent
commit
8aaf9b5cd4
  1. 3
      README.md
  2. 12
      src/middlewares/install.js
  3. 40
      src/utils/router.js

3
README.md

@ -9,4 +9,5 @@
- [x] 数据库 - [x] 数据库
- [ ] 缓存 - [ ] 缓存
- [ ] 界面 - [ ] 界面
- [ ] 定时任务 - [ ] 定时任务
- [ ] htmx

12
src/middlewares/install.js

@ -15,9 +15,15 @@ export default app => {
app.use( app.use(
auth({ auth({
whiteList: [ whiteList: [
{ pattern: "/", auth: "try" }, // API接口访问
"/api/login", "/api/login",
"/api/register" "/api/register",
{ pattern: "/api/v1/status", auth: "try" },
{ pattern: "/api/**/*", auth: true },
// 静态资源访问
"",
"/",
"/**/*",
], ],
blackList: [], blackList: [],
}) })

40
src/utils/router.js

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

Loading…
Cancel
Save