29 lines
862 B
TypeScript
29 lines
862 B
TypeScript
type Denied = () => void;
|
|
|
|
let onDenied: Denied | null = null;
|
|
|
|
export function setSessionDenied(handler: Denied) {
|
|
onDenied = handler;
|
|
}
|
|
|
|
function requestUrl(input: RequestInfo | URL) {
|
|
if (typeof input === "string") return input;
|
|
if (input instanceof URL) return input.href;
|
|
return input.url;
|
|
}
|
|
|
|
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
|
|
const response = await fetch(input, init);
|
|
if (requestUrl(input).includes("/api/session")) return response;
|
|
if (response.status === 401) {
|
|
onDenied?.();
|
|
return response;
|
|
}
|
|
if (response.status === 403) {
|
|
const body = await response.clone().json().catch(() => null);
|
|
const detail = body && typeof body === "object" ? (body as { detail?: unknown }).detail : "";
|
|
if (detail === "管理员不能访问该接口") onDenied?.();
|
|
}
|
|
return response;
|
|
}
|