const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1'; let apiAvailable: boolean | null = null; let probePromise: Promise | null = null; async function checkApi(): Promise { if (apiAvailable !== null) return apiAvailable; if (probePromise) return probePromise; probePromise = (async () => { try { const res = await fetch(`${API_BASE}/products`, { method: 'HEAD', signal: AbortSignal.timeout(300) }); apiAvailable = res.ok; } catch { apiAvailable = false; } return apiAvailable; })(); return probePromise; } async function request(path: string, options?: RequestInit): Promise { const available = await checkApi(); if (!available) throw new Error('API 不可用'); const res = await fetch(`${API_BASE}${path}`, { headers: { 'Content-Type': 'application/json', ...options?.headers }, ...options, }).catch(() => null); if (!res) throw new Error('API 不可用'); if (!res.ok) { const error = await res.json().catch(() => ({})); throw new Error(error.message || `请求失败: ${res.status}`); } return res.json(); } export const api = { get: (path: string) => request(path), post: (path: string, data: unknown) => request(path, { method: 'POST', body: JSON.stringify(data) }), patch: (path: string, data: unknown) => request(path, { method: 'PATCH', body: JSON.stringify(data) }), delete: (path: string) => request(path, { method: 'DELETE' }), };