/** * 后端 API 客户端。 * * 默认走同源代理:页面请求相对路径 /api/*,由 next.config.ts 的 rewrites 转发到后端 * (默认 http://127.0.0.1:8000,可用环境变量 BACKEND_API_URL 覆盖)。 * 需要直连(不走代理)时可用 NEXT_PUBLIC_API_BASE 显式指定后端地址(含 /api)。 */ const explicitBase = process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, ""); const BASE = explicitBase ?? "/api"; export async function apiGet(path: string): Promise { const resp = await fetch(`${BASE}${path}`); if (!resp.ok) throw new Error(`GET ${path} → ${resp.status}: ${await resp.text()}`); return (await resp.json()) as T; } /** * GET 并**同时拿到响应头**。 * * 为什么需要:列表接口用 `X-Total-Count` 暴露「过滤后总数」,而 body 必须保持 * `list[...]` 形状(既有页面依赖)。只读 body 的 `apiGet` 拿不到这个信息, * 会让前端无法区分「这就是全部」和「只是最近 N 条」——那正是 §7 要避免的静默截断。 */ export async function apiGetWithHeaders( path: string ): Promise<{ data: T; headers: Headers }> { const resp = await fetch(`${BASE}${path}`); if (!resp.ok) throw new Error(`GET ${path} → ${resp.status}: ${await resp.text()}`); return { data: (await resp.json()) as T, headers: resp.headers }; } /** * GET 原始文本。 * * 导出归档时用:直接落盘**后端存储的那份 JSON**,而不是前端再 `JSON.stringify` * 一遍(后者会因字段顺序/缩进差异而与归档原文不同,且多一次内存拷贝)。 */ export async function apiGetText(path: string): Promise { const resp = await fetch(`${BASE}${path}`); if (!resp.ok) throw new Error(`GET ${path} → ${resp.status}: ${await resp.text()}`); return await resp.text(); } export async function apiPost(path: string, body: unknown): Promise { const resp = await fetch(`${BASE}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!resp.ok) { const text = await resp.text(); throw new Error(`POST ${path} → ${resp.status}: ${text.slice(0, 300)}`); } return (await resp.json()) as T; } export async function apiPut(path: string, body: unknown): Promise { const resp = await fetch(`${BASE}${path}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!resp.ok) { const text = await resp.text(); throw new Error(`PUT ${path} → ${resp.status}: ${text.slice(0, 300)}`); } return (await resp.json()) as T; } /** * PATCH:局部更新(如「启用/停用因子」只改 enabled,不该把整行 PUT 回去)。 * * 为什么单列:因子参数化新增了 `PATCH /api/factors {name, enabled}` —— * 名字里有括号/等号/逗号,放路径会被代理折腾,所以放在 body 里用 PATCH。 */ export async function apiPatch(path: string, body: unknown): Promise { const resp = await fetch(`${BASE}${path}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!resp.ok) { const text = await resp.text(); throw new Error(`PATCH ${path} → ${resp.status}: ${text.slice(0, 300)}`); } return (await resp.json()) as T; } export async function apiDelete(path: string): Promise { const resp = await fetch(`${BASE}${path}`, { method: "DELETE" }); if (!resp.ok) { const text = await resp.text(); throw new Error(`DELETE ${path} → ${resp.status}: ${text.slice(0, 300)}`); } return (await resp.json().catch(() => ({}))) as T; } export interface ApiError { status: number; message: string; }