export class ApiError extends Error { readonly status: number; constructor(status: number, message: string) { super(message); this.name = "ApiError"; this.status = status; } } export const BASE = "/api/cloud"; /** Au-dela de ce seuil, l'envoi passe par des sessions morcelees. */ export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024; const messageOf = (body: unknown, fallback: string): string => (body as { error?: { message?: string } } | null)?.error?.message ?? fallback; export const request = async (path: string, init?: RequestInit): Promise => { let response: Response; try { response = await fetch(`${BASE}${path}`, { credentials: "same-origin", ...init, headers: { ...(init?.body ? { "content-type": "application/json" } : {}), ...init?.headers, }, }); } catch { throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); } const body: unknown = await response.json().catch(() => null); if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue.")); return body as T; }; export const get = (path: string): Promise => request(path); export const post = (path: string, payload?: unknown): Promise => request(path, { method: "POST", ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), }); export const patch = (path: string, payload: unknown): Promise => request(path, { method: "PATCH", body: JSON.stringify(payload) }); export const put = (path: string, payload?: unknown): Promise => request(path, { method: "PUT", ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), }); export const del = (path: string): Promise => request(path, { method: "DELETE" }); export const query = (params: Record): string => { const search = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value !== null && value !== undefined && value !== "") search.set(key, String(value)); } const suffix = search.toString(); return suffix ? `?${suffix}` : ""; }; export const putBinary = async (path: string, body: BodyInit, type: string): Promise => { let response: Response; try { response = await fetch(`${BASE}${path}`, { method: "PUT", credentials: "same-origin", headers: type ? { "content-type": type } : {}, body, }); } catch { throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); } const parsed: unknown = await response.json().catch(() => null); if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue.")); return parsed as T; };