export class ApiError extends Error { constructor( public status: number, message: string, ) { super(message); } } export async function api( path: string, options: RequestInit = {}, ): Promise { const token = sessionStorage.getItem("session"); let res: Response; try { res = await fetch("/api" + path, { signal: AbortSignal.timeout(15000), ...options, headers: { ...(options.body instanceof FormData ? {} : { "Content-Type": "application/json" }), ...(token ? { Authorization: "Bearer " + token } : {}), ...options.headers, }, }); } catch { throw new ApiError(503, "无法连接后端服务,请检查服务是否启动"); } const data = await res.json().catch(() => ({ message: res.status >= 500 ? "后端服务未就绪,请检查服务与数据库连接" : "服务响应格式异常", })); if (!res.ok) throw new ApiError(res.status, data.message || "操作失败,请稍后重试"); return data; } export const body = (v: unknown) => JSON.stringify(v);