Browse Source

feat: 重构用户控制器,添加自动注册路由功能,更新中间件路径

route
谢亚昕 1 month ago
parent
commit
ea8a70c43d
  1. 2
      src/controllers/AuthController.js
  2. 9
      src/middlewares/install.js
  3. 56
      src/utils/ForRegister.js
  4. 23
      src/utils/router.js

2
src/controllers/userController.js → src/controllers/AuthController.js

@ -36,7 +36,7 @@ export const login = async (ctx) => {
import Router from "utils/router.js"
export function createRoutes() {
const router = new Router({ prefix: "/api" })
router.get("/hello", hello)
router.get("/hello", hello, { auth: false })
router.get("/user/:id", getUser)
router.post("/register", register)
router.post("/login", login)

9
src/middlewares/install.js

@ -7,7 +7,7 @@ import ErrorHandler from "./ErrorHandler"
import { auth } from "./Auth"
import bodyParser from "koa-bodyparser"
import Views from "./Views"
import { autoRegisterControllers } from "utils/autoRegister.js"
import { autoRegisterControllers } from "@/utils/ForRegister.js"
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const publicPath = resolve(__dirname, "../../public")
@ -18,12 +18,7 @@ export default app => {
app.use(
auth({
whiteList: [
// // API接口访问
// "/api/login",
// "/api/register",
// { pattern: "/api/v1/status", auth: "try" },
// { pattern: "/api/**/*", auth: true },
// // 静态资源访问
// 所有请求放行
{ pattern: "/", auth: false },
{ pattern: "/**/*", auth: false },
],

56
src/utils/autoRegister.js → src/utils/ForRegister.js

@ -37,34 +37,34 @@ export function autoRegisterControllers(app, controllersDir = path.resolve(__dir
;(async () => {
await scan(controllersDir)
// TODO: 存在问题:每个Controller都是有顺序的,如果其中一个Controller没有next方法,可能会导致后续的Controller无法执行
// allRouter.forEach(router => {
// app.use(router.middleware())
// })
// 聚合中间件:只分发到匹配的router
app.use(async (ctx, next) => {
let matched = false
for (const router of allRouter) {
// router._matchRoute 只在 router.js 内部,需暴露或用 middleware 包一层
if (typeof router._matchRoute === "function") {
const route = router._matchRoute(ctx.method.toLowerCase(), ctx.path)
if (route) {
matched = true
await router.middleware()(ctx, next)
break // 命中一个即停止
}
} else {
// fallback: 直接尝试middleware,若未命中会自动next
const before = ctx.status
await router.middleware()(ctx, next)
if (ctx.status !== before) {
matched = true
break
}
}
}
if (!matched) {
await next()
}
allRouter.forEach(router => {
app.use(router.middleware())
})
// // 聚合中间件:只分发到匹配的router
// app.use(async (ctx, next) => {
// let matched = false
// for (const router of allRouter) {
// // router._matchRoute 只在 router.js 内部,需暴露或用 middleware 包一层
// if (typeof router._matchRoute === "function") {
// const route = router._matchRoute(ctx.method.toLowerCase(), ctx.path)
// if (route) {
// matched = true
// await router.middleware()(ctx, next)
// break // 命中一个即停止
// }
// } else {
// // fallback: 直接尝试middleware,若未命中会自动next
// const before = ctx.status
// await router.middleware()(ctx, next)
// if (ctx.status !== before) {
// matched = true
// break
// }
// }
// }
// if (!matched) {
// await next()
// }
// })
})()
}

23
src/utils/router.js

@ -32,9 +32,9 @@ class Router {
* 注册GET路由支持中间件链
* @param {string} path - 路由路径
* @param {Function} handler - 中间件和处理函数
* @param {...Object} others - 其他参数可选
* @param {Object} others - 其他参数可选
*/
get(path, handler, ...others) {
get(path, handler, others) {
this._registerRoute("get", path, handler, others)
}
@ -42,23 +42,23 @@ class Router {
* 注册POST路由支持中间件链
* @param {string} path - 路由路径
* @param {Function} handler - 中间件和处理函数
* @param {...Object} others - 其他参数可选
* @param {Object} others - 其他参数可选
*/
post(path, handler, ...others) {
post(path, handler, others) {
this._registerRoute("post", path, handler, others)
}
/**
* 注册PUT路由支持中间件链
*/
put(path, handler, ...others) {
put(path, handler, others) {
this._registerRoute("put", path, handler, others)
}
/**
* 注册DELETE路由支持中间件链
*/
delete(path, handler, ...others) {
delete(path, handler, others) {
this._registerRoute("delete", path, handler, others)
}
@ -89,6 +89,7 @@ class Router {
// 组合全局中间件、路由专属中间件和 handler
const middlewares = [...this.middlewares];
if (route) {
// 如果匹配到路由,添加路由专属中间件和处理函数
ctx.params = route.params;
let isAuth = this.options.auth;
@ -98,13 +99,13 @@ class Router {
middlewares.push(RouteAuth({ auth: isAuth }));
middlewares.push(route.handler)
// 用 koa-compose 组合
const composed = compose(middlewares);
await composed(ctx, next);
} else {
middlewares.push(RouteAuth({ auth: this.options.auth }));
// 如果没有匹配到路由,直接调用 next
await next();
}
// 用 koa-compose 组合
const composed = compose(middlewares);
await composed(ctx, next);
};
}

Loading…
Cancel
Save