Files
2026Technology-Competition/frontend/src/api.ts
T

20 lines
744 B
TypeScript

import type { ApiErrorBody } from './types.ts';
/** 类型化 fetch 封装:非 2xx 抛 Error(后端 detail.message)。 */
export async function api<T = unknown>(method: string, url: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = {};
const opt: RequestInit = { method, headers };
if (body !== undefined) {
headers['Content-Type'] = 'application/json';
opt.body = JSON.stringify(body);
}
const r = await fetch(url, opt);
const data = (await r.json().catch(() => ({}))) as T & ApiErrorBody;
if (!r.ok) {
const detail = data.detail;
const msg = typeof detail === 'string' ? detail : detail && detail.message;
throw new Error(msg || String(r.status));
}
return data as T;
}