const BASE = '/api' function getToken() { return localStorage.getItem('token') } async function request(path: string, options: RequestInit = {}): Promise { const token = getToken() const res = await fetch(`${BASE}${path}`, { ...options, headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...options.headers, }, }) if (res.status === 401) { localStorage.removeItem('token') localStorage.removeItem('user') window.location.href = '/login' throw new Error('Session expirée') } if (!res.ok) { const err = await res.json().catch(() => ({ error: res.statusText })) throw new Error(err.error || res.statusText) } if (res.status === 204) return undefined as T const json = await res.json() return json.data !== undefined ? json.data : json } export const api = { get: (path: string) => request(path), post: (path: string, body?: unknown) => request(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined }), put: (path: string, body?: unknown) => request(path, { method: 'PUT', body: body ? JSON.stringify(body) : undefined }), delete: (path: string) => request(path, { method: 'DELETE' }), }