const BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5270' async function request(path, options = {}) { const res = await fetch(`${BASE_URL}${path}`, { headers: { 'Content-Type': 'application/json', ...options.headers }, ...options, }) const envelope = await res.json() if (!res.ok || !envelope.success) { const msg = envelope.error?.message ?? `API ${res.status}: ${path}` throw new Error(msg) } return envelope.data } /** Returns null when the resource does not exist yet (HTTP 404 or empty optional payload). */ async function requestOptional(path) { const res = await fetch(`${BASE_URL}${path}`, { headers: { 'Content-Type': 'application/json' }, }) const envelope = await res.json() if (res.status === 404) return null if (!res.ok || !envelope.success) { const msg = envelope.error?.message ?? `API ${res.status}: ${path}` throw new Error(msg) } return envelope.data ?? null } export const api = { get: (path) => request(path), getOptional: (path) => requestOptional(path), post: (path, body) => request(path, { method: 'POST', body: body !== undefined ? JSON.stringify(body) : undefined, }), }