/** * Composable for API calls to the FastAPI backend. */ export function useApi() { const config = useRuntimeConfig() const baseURL = config.public.apiBase as string function getToken(): string | null { if (import.meta.client) { return localStorage.getItem('sejeteralo_token') } return null } async function apiFetch( path: string, options: RequestInit = {}, ): Promise { const headers: Record = { ...(options.headers as Record || {}), } const token = getToken() if (token) { headers['Authorization'] = `Bearer ${token}` } if (options.body && !(options.body instanceof FormData)) { headers['Content-Type'] = 'application/json' } let response: Response try { response = await fetch(`${baseURL}${path}`, { ...options, headers, }) } catch (err) { throw new Error(`Impossible de contacter le serveur (${baseURL}). Vérifiez que le backend est lancé.`) } if (!response.ok) { const error = await response.json().catch(() => ({ detail: response.statusText })) throw new Error(error.detail || `Erreur API ${response.status}`) } const text = await response.text() if (!text) return {} as T return JSON.parse(text) } return { get: (path: string) => apiFetch(path), post: (path: string, body?: unknown) => apiFetch(path, { method: 'POST', body: body instanceof FormData ? body : JSON.stringify(body), }), put: (path: string, body?: unknown) => apiFetch(path, { method: 'PUT', body: JSON.stringify(body), }), delete: (path: string) => apiFetch(path, { method: 'DELETE' }), } }