usePerms.ts
1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"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),
};
}