const baseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:3000'; export class ApiError extends Error { constructor( readonly status: number, message: string, ) { super(message); this.name = 'ApiError'; } } type ApiOptions = RequestInit & { token?: string; }; export async function api(path: string, options: ApiOptions = {}): Promise { const headers: Record = { 'Content-Type': 'application/json', ...(options.headers as Record | undefined), }; if (options.token) { headers.Authorization = `Bearer ${options.token}`; } const { token: _token, ...fetchOptions } = options; const res = await fetch(`${baseUrl}${path}`, { ...fetchOptions, headers, }); if (!res.ok) { const body = (await res.json().catch(() => null)) as | { message?: string | string[] } | null; const msg = Array.isArray(body?.message) ? body.message.join(', ') : body?.message ?? res.statusText; throw new ApiError(res.status, msg); } if (res.status === 204) { return undefined as T; } return res.json() as Promise; }