Skip to content

Commit

Permalink
simplify handleResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
bh2smith committed Jul 2, 2024
1 parent 99c5b22 commit 795d964
Showing 1 changed file with 5 additions and 24 deletions.
29 changes: 5 additions & 24 deletions src/api/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,39 +54,20 @@ export class Router {
}

protected async _handleResponse<T>(responsePromise: Promise<Response>): Promise<T> {
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<T>(
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 795d964

Please sign in to comment.