diff --git a/lib/upload-api.ts b/lib/upload-api.ts index 72efbce..c3a7b91 100644 --- a/lib/upload-api.ts +++ b/lib/upload-api.ts @@ -27,6 +27,8 @@ type UploadJsonBody = | { stagingId: string } | { stagingId: string; action: DriveAction } +const RESPONSE_PREVIEW_MAX_LENGTH = 160 + function getApiError(data: unknown, fallback: string) { return isRecord(data) && typeof data.error === 'string' ? data.error : fallback } @@ -48,6 +50,50 @@ function getUploadJsonHeaders(secret: string) { } } +function getResponsePreview(body: string) { + return body + .replace(/<[^>]*>/g, ' ') + .replace(/\s+/g, ' ') + .trim() + .slice(0, RESPONSE_PREVIEW_MAX_LENGTH) +} + +function getUnexpectedJsonResponseError(res: Response, body: string) { + const contentType = res.headers.get('content-type') || 'type inconnu' + const preview = getResponsePreview(body) + const detail = preview ? ` Detail : ${preview}` : '' + + if (res.status === 413) { + return `Upload trop volumineux ou bloque par le proxy (${res.status}). Verifiez la limite de taille Coolify/Nginx.${detail}` + } + + if (res.status === 502 || res.status === 503 || res.status === 504) { + return `API upload indisponible (${res.status}). Le serveur a probablement redemarre ou plante pendant le traitement.${detail}` + } + + return `Reponse serveur inattendue (${res.status}, ${contentType}).${detail}` +} + +async function readUploadJson(res: Response): Promise { + const body = await res.text() + + if (body.trim() === '') { + return {} + } + + const contentType = res.headers.get('content-type') || '' + + if (!contentType.toLowerCase().includes('json')) { + throw new Error(getUnexpectedJsonResponseError(res, body)) + } + + try { + return JSON.parse(body) + } catch { + throw new Error(getUnexpectedJsonResponseError(res, body)) + } +} + async function postUploadJson( endpoint: string, secret: string, @@ -61,7 +107,7 @@ async function postUploadJson( signal, }) - const data: unknown = await res.json() + const data = await readUploadJson(res) return { res, data } } @@ -165,7 +211,7 @@ export async function stageUpload( signal, }) - const data: unknown = await res.json() + const data = await readUploadJson(res) if (!res.ok || !isSuccessfulUploadData(data)) { throw new Error(getApiError(data, `Erreur serveur (${res.status})`))