2026-02-16 13:32:04 -06:00
|
|
|
const BASE = "/api";
|
|
|
|
|
|
|
|
|
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
2026-02-20 10:33:10 -06:00
|
|
|
const headers = new Headers(init?.headers ?? undefined);
|
|
|
|
|
const body = init?.body;
|
|
|
|
|
if (!(body instanceof FormData) && !headers.has("Content-Type")) {
|
|
|
|
|
headers.set("Content-Type", "application/json");
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-16 13:32:04 -06:00
|
|
|
const res = await fetch(`${BASE}${path}`, {
|
2026-02-20 10:33:10 -06:00
|
|
|
headers,
|
2026-02-16 13:32:04 -06:00
|
|
|
...init,
|
|
|
|
|
});
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
const body = await res.json().catch(() => null);
|
|
|
|
|
throw new Error(body?.error ?? `Request failed: ${res.status}`);
|
|
|
|
|
}
|
|
|
|
|
return res.json();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const api = {
|
|
|
|
|
get: <T>(path: string) => request<T>(path),
|
|
|
|
|
post: <T>(path: string, body: unknown) =>
|
|
|
|
|
request<T>(path, { method: "POST", body: JSON.stringify(body) }),
|
2026-02-20 10:33:10 -06:00
|
|
|
postForm: <T>(path: string, body: FormData) =>
|
|
|
|
|
request<T>(path, { method: "POST", body }),
|
2026-02-16 13:32:04 -06:00
|
|
|
patch: <T>(path: string, body: unknown) =>
|
|
|
|
|
request<T>(path, { method: "PATCH", body: JSON.stringify(body) }),
|
|
|
|
|
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
|
|
|
|
|
};
|