Files
gitlab-instance-0a899031_cn…/app/lib/api-client.ts
root 283d65d1d1 ;s
2026-06-07 12:48:17 +08:00

33 lines
953 B
TypeScript

export const API_BASE = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
export function apiUrl(path: string): string {
if (/^https?:\/\//i.test(path)) return path;
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
if (API_BASE.endsWith("/api") && normalizedPath.startsWith("/api/")) {
return `${API_BASE}${normalizedPath.slice(4)}`;
}
return `${API_BASE}${normalizedPath}`;
}
export async function apiFetch<T>(
path: string,
init?: RequestInit
): Promise<T> {
const res = await fetch(apiUrl(path), {
credentials: "include",
...init,
headers:
init?.body instanceof FormData
? init.headers
: {
"Content-Type": "application/json",
...(init?.headers || {}),
},
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data?.detail || data?.error || `HTTP ${res.status}`);
}
return data as T;
}