import { ApiException, type ApiError } from './types' const BASE = '' // 同源;dev 走 vite proxy const DEFAULT_TIMEOUT_MS = 30_000 interface RequestOptions { method?: 'GET' | 'POST' | 'PATCH' | 'DELETE' body?: unknown signal?: AbortSignal } let authTokenProvider: () => string | null = () => null let onUnauthorized: () => void = () => {} export function configure(opts: { tokenProvider: () => string | null onUnauthorized: () => void }) { authTokenProvider = opts.tokenProvider onUnauthorized = opts.onUnauthorized } export async function request(path: string, opts: RequestOptions = {}): Promise { const headers: Record = { 'Content-Type': 'application/json', 'X-Client-Request-ID': crypto.randomUUID(), } const token = authTokenProvider() if (token) headers['Authorization'] = `Bearer ${token}` const controller = new AbortController() const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS) if (opts.signal) { if (opts.signal.aborted) { controller.abort() } else { opts.signal.addEventListener('abort', () => controller.abort(), { once: true }) } } try { const resp = await fetch(BASE + path, { method: opts.method || 'GET', headers, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, signal: controller.signal, }) if (resp.status === 401) { onUnauthorized() } if (resp.status === 204) { return undefined as T } const text = await resp.text() const data = text ? JSON.parse(text) : null if (!resp.ok) { throw new ApiException( resp.status, (data as ApiError) || { code: 'unknown', message: resp.statusText }, ) } return data as T } finally { clearTimeout(timer) } }