Browse Source

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

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

1
README.md

@ -10,3 +10,4 @@
- [ ] 缓存
- [ ] 界面
- [ ] 定时任务
- [ ] htmx

10
src/middlewares/install.js

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

40
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 });
}
/**

Loading…
Cancel
Save