JavaScript中如何在Route类子方法中获取父级路由group的前缀值?
实现方案
你可以通过给Route类加静态前缀栈的方式实现分组上下文的传递,逻辑如下:
- 调用
group方法时先把当前分组前缀压入栈 - 同步执行分组的回调函数,回调内的所有路由方法执行时,都会拼接栈内所有前缀生成完整路由路径
- 回调执行完毕后将当前前缀弹出栈,退出当前分组上下文,避免污染外层路由定义
完整代码示例
interface IRoute { path: string; method: string; handler: Function; } export class Route { // 存储所有已定义的路由 static #routes: Array<IRoute> = []; // 存储分组前缀的栈,维护当前上下文的前缀层级 static #prefixStack: string[] = []; public static group(prefix: string, cb: Function) { // 前缀入栈,进入当前分组上下文 this.#prefixStack.push(prefix); // 执行分组内的路由定义逻辑 cb(); // 前缀出栈,退出当前分组上下文 this.#prefixStack.pop(); } public static get(path: string, handler: Function) { // 拼接所有前缀+当前路径,自动处理多余斜杠 const fullPath = [...this.#prefixStack, path].join('').replace(/\/+/g, '/'); this.#routes.push({ path: fullPath, method: 'GET', handler }); } // post/put/delete等其他请求方法逻辑和get完全一致,按需扩展即可 // 对外暴露所有路由,用于后续注册到Express实例 public static getAllRoutes() { return this.#routes; } }
使用示例
和你预期的写法完全一致,还支持多层嵌套分组:
Route.group("/api", () => { Route.get("/auth/login", myLoginFunction) Route.get("/auth/register", myRegisterFunction) // 嵌套分组 Route.group("/admin", () => { Route.get("/dashboard", adminDashboardHandler) }) })
最终生成的路由路径为:
/api/auth/login/api/auth/register/api/admin/dashboard
注意事项
该方案依赖分组回调的同步执行,不要在group的回调内写异步的路由定义逻辑,否则会导致前缀栈弹出时机错误,无法正确拼接路径。常规的同步定义路由的场景完全可以覆盖。
内容的提问来源于stack exchange,提问作者user14850280
相关产品推荐
相关产品推荐

