s''
This commit is contained in:
29
app/lib/api-client.ts
Normal file
29
app/lib/api-client.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export const API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:8000";
|
||||
|
||||
export function apiUrl(path: string): string {
|
||||
if (/^https?:\/\//i.test(path)) return path;
|
||||
return `${API_BASE}${path.startsWith("/") ? path : `/${path}`}`;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user