// Mini client REST : JSON, cookies de session, erreurs API normalisées. import type { ApiError as ApiErrorBody } from '@arboretum/shared'; export class ApiError extends Error { constructor( readonly status: number, readonly code: string, message: string, ) { super(message); this.name = 'ApiError'; } } async function request(path: string, method: string, body?: unknown): Promise { const init: RequestInit = { method, credentials: 'same-origin' }; if (body !== undefined) { init.headers = { 'content-type': 'application/json' }; init.body = JSON.stringify(body); } const res = await fetch(path, init); if (!res.ok) { let parsed: ApiErrorBody | null = null; try { parsed = (await res.json()) as ApiErrorBody; } catch { // réponse non-JSON : on retombe sur le statusText } throw new ApiError(res.status, parsed?.error.code ?? 'UNKNOWN', parsed?.error.message ?? res.statusText); } return (await res.json()) as T; } export const api = { get: (path: string): Promise => request(path, 'GET'), post: (path: string, body?: unknown): Promise => request(path, 'POST', body), delete: (path: string): Promise => request(path, 'DELETE'), };