From 795d964fd8901b592ade6d2ede475b79be4b2643 Mon Sep 17 00:00:00 2001 From: Benjamin Smith Date: Tue, 2 Jul 2024 08:19:42 +0200 Subject: [PATCH] simplify handleResponse --- src/api/router.ts | 29 +++++------------------------ 1 file changed, 5 insertions(+), 24 deletions(-) diff --git a/src/api/router.ts b/src/api/router.ts index c10c21b..5b0bad7 100644 --- a/src/api/router.ts +++ b/src/api/router.ts @@ -54,39 +54,20 @@ export class Router { } protected async _handleResponse(responsePromise: Promise): Promise { - let result; try { const response = await responsePromise; - if (!response.ok) { - log.error( - logPrefix, - `response error ${response.status} - ${response.statusText}`, - ); - } - const clonedResponse = response.clone(); - try { - // Attempt to parse JSON - result = await response.json(); - } catch { - // Fallback to text if JSON parsing fails - // This fallback is used for CSV retrieving methods. - result = await clonedResponse.text(); - } - - // Check for error in result after parsing - if (result.error) { - log.error(logPrefix, `error contained in response ${JSON.stringify(result)}`); - // Assuming DuneError is a custom Error you'd like to throw + const errorText = await response.text(); throw new DuneError( - result.error instanceof Object ? result.error.type : result.error, + `HTTP error! Status: ${response.status}, Message: ${errorText}`, ); } + + return (await response.json()) as T; } catch (error) { log.error(logPrefix, `caught unhandled response error ${JSON.stringify(error)}`); throw new DuneError(`Response ${error}`); } - return result; } protected async _request( @@ -119,7 +100,7 @@ export class Router { /// Build Url Search Parameters on GET if (method === "GET" && payload) { const searchParams = new URLSearchParams(payloadSearchParams(payload)).toString(); - pathParams = `?${searchParams}`; + pathParams = searchParams ? `?${searchParams}` : ""; } log.debug("Final request URL", url + pathParams); const response = fetch(url + pathParams, requestData);