Files
mitwirkung/apps/web/src/api.ts

20 lines
743 B
TypeScript

async function request<T>(path: string, options?: RequestInit): Promise<T> {
const response = await fetch(path, {
credentials: "include",
headers: { "Content-Type": "application/json", ...options?.headers },
...options,
});
if (!response.ok) {
const error = await response.json().catch(() => ({ message: "Die Anfrage ist fehlgeschlagen." }));
throw new Error(error.message || "Die Anfrage ist fehlgeschlagen.");
}
if (response.status === 204) return undefined as T;
return response.json();
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, { method: "POST", body: body === undefined ? undefined : JSON.stringify(body) }),
};