30 lines
855 B
TypeScript
30 lines
855 B
TypeScript
/** 全局认证 fetch 客户端 */
|
|
|
|
let tokenGetter: () => string | null = () => null;
|
|
|
|
export function setTokenGetter(fn: () => string | null) {
|
|
tokenGetter = fn;
|
|
}
|
|
|
|
export async function fetchAuthenticated(url: string, options?: RequestInit): Promise<Response> {
|
|
const token = tokenGetter();
|
|
const res = await fetch(url, {
|
|
...options,
|
|
headers: {
|
|
...options?.headers,
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
},
|
|
});
|
|
if (res.status === 401) {
|
|
window.dispatchEvent(new CustomEvent('auth:unauthorized'));
|
|
throw new Error('Unauthorized');
|
|
}
|
|
return res;
|
|
}
|
|
|
|
export async function fetchJson<T>(url: string, options?: RequestInit): Promise<T> {
|
|
const res = await fetchAuthenticated(url, options);
|
|
if (!res.ok) throw new Error(`API error: ${res.status} ${res.statusText}`);
|
|
return res.json();
|
|
}
|