仰望星辰工作室

miaopanel

miaopanel/ web/src/api.ts 2.8 KB · 108 行 原始文件
1export class ApiError extends Error {
2 status: number
3 constructor(message: string, status: number) {
4 super(message)
5 this.status = status
6 }
7}
8
9let csrfToken = ''
10
11export function setCsrf(token: string) {
12 csrfToken = token
13}
14
15export function getCsrf() {
16 return csrfToken
17}
18
19let unauthorizedHandler: (() => void) | null = null
20let sessionRefresher: (() => Promise<void>) | null = null
21
22/** Called once per expired-session response so the shell can show the login. */
23export function setUnauthorizedHandler(fn: () => void) {
24 unauthorizedHandler = fn
25}
26
27/** Used to fetch a fresh CSRF token before retrying a rejected request. */
28export function setSessionRefresher(fn: () => Promise<void>) {
29 sessionRefresher = fn
30}
31
32/** Lets streaming code reuse the shell's expired-session handling. */
33export function triggerUnauthorized() {
34 unauthorizedHandler?.()
35}
36
37interface Envelope<T> {
38 code: number
39 msg: string
40 data: T
41}
42
43async function request<T>(
44 method: string,
45 path: string,
46 body?: unknown,
47 allowRetry = true,
48): Promise<T> {
49 const headers: Record<string, string> = {}
50 if (body !== undefined) headers['Content-Type'] = 'application/json'
51 if (method !== 'GET') headers['X-CSRF-Token'] = csrfToken
52
53 let res: Response
54 try {
55 res = await fetch(path, {
56 method,
57 headers,
58 credentials: 'same-origin',
59 body: body === undefined ? undefined : JSON.stringify(body),
60 })
61 } catch {
62 throw new ApiError('无法连接面板,请检查网络或服务状态', 0)
63 }
64
65 let env: Envelope<T> | null = null
66 try {
67 env = (await res.json()) as Envelope<T>
68 } catch {
69 env = null
70 }
71
72 if (res.status === 401) {
73 unauthorizedHandler?.()
74 throw new ApiError(env?.msg || '登录已过期,请重新登录', 401)
75 }
76
77 // The session cookie may outlive a server-side restart of the CSRF secret;
78 // one silent refresh avoids a confusing "请刷新页面" toast.
79 if (
80 res.status === 403 &&
81 allowRetry &&
82 sessionRefresher &&
83 /CSRF/i.test(env?.msg ?? '')
84 ) {
85 try {
86 await sessionRefresher()
87 return await request<T>(method, path, body, false)
88 } catch {
89 /* fall through to the original error */
90 }
91 }
92
93 if (!env) {
94 throw new ApiError(`服务器返回异常 (HTTP ${res.status})`, res.status)
95 }
96 if (!res.ok || env.code !== 0) {
97 throw new ApiError(env.msg || `请求失败 (HTTP ${res.status})`, res.status)
98 }
99 return env.data
100}
101
102export const api = {
103 get: <T>(path: string) => request<T>('GET', path),
104 post: <T>(path: string, body?: unknown) => request<T>('POST', path, body ?? {}),
105 put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body ?? {}),
106 patch: <T>(path: string, body?: unknown) => request<T>('PATCH', path, body ?? {}),
107 del: <T>(path: string) => request<T>('DELETE', path),
108}