usePerms.ts 1.76 KB
"use client";

import { useEffect, useState } from "react";

import { fetchMyPerms, hasPerm, type MenuNode } from "@/lib/auth";

interface PermState {
  loaded: boolean;
  isSuperadmin: boolean;
  perms: string[];
  menus: MenuNode[];
}

const EMPTY: PermState = { loaded: false, isSuperadmin: false, perms: [], menus: [] };

// 模块级缓存:整个应用只拉一次 /oa/me/perms(登录/登出后调用 resetPerms 失效)。
let cache: PermState | null = null;
let inflight: Promise<PermState> | null = null;
const listeners = new Set<(s: PermState) => void>();

async function ensure(): Promise<PermState> {
  if (cache) return cache;
  if (!inflight) {
    inflight = fetchMyPerms()
      .then((d) => {
        cache = { loaded: true, isSuperadmin: d.isSuperadmin, perms: d.perms, menus: d.menus };
        listeners.forEach((l) => l(cache!));
        return cache;
      })
      .catch(() => {
        cache = { ...EMPTY, loaded: true };
        listeners.forEach((l) => l(cache!));
        return cache;
      })
      .finally(() => {
        inflight = null;
      });
  }
  return inflight;
}

/** 登录/登出后调用,清空权限缓存以便下次重新拉取。 */
export function resetPerms() {
  cache = null;
  inflight = null;
}

/** 权限 hook:返回当前用户的 perm 集合、菜单树与判定函数。 */
export function usePerms() {
  const [state, setState] = useState<PermState>(cache ?? EMPTY);

  useEffect(() => {
    let alive = true;
    const listener = (s: PermState) => alive && setState(s);
    listeners.add(listener);
    ensure().then((s) => alive && setState(s));
    return () => {
      alive = false;
      listeners.delete(listener);
    };
  }, []);

  return {
    ...state,
    has: (code: string) => hasPerm(state.perms, code),
  };
}