menu.ts 2.22 KB
// 菜单树接口(后端 /system/menu/tree,需登录态)
// 继承 ApiClient,共享 http 与 RSA 加签/验签。
import { ApiClient } from '../core/client';

/**
 * 后端菜单节点。
 * nodeType:1-产品分组(permCode 为 null) 2-页面菜单(:view 码) 3-按钮操作点(动作码)
 * 后端只下发 label / permCode / sort / status,**不下发前端 route path 与 icon**,
 * 这两项由前端在 adapter 的 MENU_ROUTE_MAP 中按 permCode 登记。
 */
export interface MenuNode {
  id: number;
  parentId: number;
  label: string;
  permCode: string | null;
  nodeType: 1 | 2 | 3;
  product?: string;
  /** 同级排序,升序 */
  sort: number;
  /** 1-启用;非 1 视为停用 */
  status: number;
  children: MenuNode[];
}

class Menu extends ApiClient {
  /**
   * 菜单树的请求缓存(同一登录态内菜单树不会变,没必要重复打网络)。
   *
   * 需要它的两个真实原因:
   *  1) 开发期 React.StrictMode 会把 effect 跑成 mount → cleanup → mount,直接双发请求;
   *  2) 权限点 points 会变化(AccessProvider 挂载后异步 auth.info() 返回再 applyLogin 一次),
   *     BasicLayout 的 effect 依赖 points,points 一变就会重跑。
   *
   * 缓存的是「网络请求」,不是「菜单结果」:调用方仍用当前 points 重新 buildMenus,
   * 所以权限点更新后菜单过滤依旧准确,只是不会重复请求。
   */
  private treePromise: Promise<MenuNode[]> | null = null;

  /**
   * 当前登录用户的菜单树。
   * 后端已按角色装配;前端仍与登录下发的 permCodes 取交集后再渲染(双保险,
   * 避免后端未过滤时越权菜单被渲染出来)。
   */
  tree(): Promise<MenuNode[]> {
    if (!this.treePromise) {
      this.treePromise = this.get<MenuNode[]>('/system/menu/tree').catch((e) => {
        // 失败不缓存:允许后续重试(接口未就绪、令牌过期后重新拉取)
        this.treePromise = null;
        throw e;
      });
    }
    return this.treePromise;
  }

  /** 退出登录 / 切换账号时必须调用:菜单树随角色变化,缓存需失效 */
  clearCache() {
    this.treePromise = null;
  }
}

export const menu = new Menu();