Spaces:
Sleeping
Sleeping
File size: 2,179 Bytes
2321823 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | function getPublicUiError(status: number): string {
// Message volontairement generique pour eviter les erreurs techniques en UI.
if (status === 429) {
return "Service momentanément indisponible. Merci de réessayer.";
}
return "Une erreur temporaire est survenue. Merci de réessayer.";
}
function extractApiMessage(payload: unknown, status: number): string {
// Priorite aux messages explicites fournis par l'API.
if (payload && typeof payload === "object") {
const record = payload as Record<string, unknown>;
const detail = record.detail;
if (typeof detail === "string" && detail.trim()) {
return detail;
}
if (detail && typeof detail === "object") {
const detailRecord = detail as Record<string, unknown>;
if (typeof detailRecord.message === "string" && detailRecord.message.trim()) {
return detailRecord.message;
}
}
}
return getPublicUiError(status);
}
async function readJsonSafely(response: Response): Promise<unknown | null> {
// Evite les crashes JSON.parse quand le backend repond en texte/plain.
const raw = await response.text();
if (!raw) {
return null;
}
try {
return JSON.parse(raw);
} catch {
return null;
}
}
export async function postJson<T>(url: string, body: unknown): Promise<T> {
// Client HTTP robuste: jamais d'erreur de parsing brute exposee a l'utilisateur.
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await readJsonSafely(response);
if (!response.ok) {
throw new Error(extractApiMessage(data, response.status));
}
if (data === null) {
throw new Error(getPublicUiError(500));
}
return data as T;
}
export async function getJson<T>(url: string): Promise<T> {
// Lecture GET robuste avec meme convention de message UI.
const response = await fetch(url, { method: "GET" });
const data = await readJsonSafely(response);
if (!response.ok) {
throw new Error(extractApiMessage(data, response.status));
}
if (data === null) {
throw new Error(getPublicUiError(500));
}
return data as T;
}
|