From 4d501f9112341b5b7340401f32608bc216650b77 Mon Sep 17 00:00:00 2001 From: Damir Modyarov Date: Sun, 12 May 2024 16:50:00 +0300 Subject: [PATCH] fix: Improve api fallback --- src/request.ts | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/request.ts b/src/request.ts index 1ba7020..378e8f6 100644 --- a/src/request.ts +++ b/src/request.ts @@ -35,13 +35,18 @@ export const fetchMedia = async ( url: string, lang?: string, isAudioOnly?: boolean, - fails?: number[], + fails?: string[], }, ): Promise> => { if (fails.length >= env.API_BASE_URL.length) throw new Error(`fetch failed with ${fails}`) - - const res = await fetch(`${env.API_BASE_URL[fails.length]}/json`, { + + const currentBaseUrl = env.API_BASE_URL[fails.length] + const next = async (reason: string) => await fetchMedia( + { url, lang, isAudioOnly, fails: [...fails, `${currentBaseUrl} - ${reason}`] }, + ) + + const res = await fetch(`${currentBaseUrl}/json`, { method: "POST", headers: [ ["Accept", "application/json"], @@ -50,15 +55,13 @@ export const fetchMedia = async ( ], body: JSON.stringify({ url, isAudioOnly, filenamePattern: "basic", isNoTTWatermark: true }), }) - if (res.status >= 500) { - return await fetchMedia( - { url, lang, isAudioOnly, fails: [...fails, res.status] }, - ) - } - - const body = await res.json() + if (!res.ok) return next(`not ok (${res.status})`) + + const body = await res.json().catch(() => null) + const data = mediaResponseSchema.safeParse(body) + if (!data.success) return next("invalid response body") - return mediaResponseSchema.parse(body) + return data.data } // Stream