Skip to content

Commit

Permalink
improve api request handling
Browse files Browse the repository at this point in the history
  • Loading branch information
narthur committed Jan 12, 2025
1 parent a0902c8 commit 1fcec2f
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 63 deletions.
86 changes: 43 additions & 43 deletions src/lib/api/fetchApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,55 +6,55 @@ const API_URL =
process.env.NEXT_PUBLIC_API_URL ||
'https://graphql-staging.audioverse.org/graphql';

const getResponse = manageAsyncFunction(
(
headers: HeadersInit,
query: string,
variables: unknown,
): Promise<Response> => {
const body = JSON.stringify({
query,
variables,
});
const getResponse = (
headers: HeadersInit,
query: string,
variables: unknown,
): Promise<Response> => {
const body = JSON.stringify({
query,
variables,
});

return fetch(API_URL, {
method: 'POST',
headers,
body,
});
},
);
return fetch(API_URL, {
method: 'POST',
headers,
body,
});
};

const fetchJson = async ({
headers,
query,
variables,
}: {
headers: HeadersInit;
query: string;
variables: unknown;
}) => {
const res = await getResponse(headers, query, variables);
const fetchJson = manageAsyncFunction(
async ({
headers,
query,
variables,
}: {
headers: HeadersInit;
query: string;
variables: unknown;
}) => {
const res = await getResponse(headers, query, variables);

if (!res.ok) {
console.error({ text: await res.text(), res, query, variables, headers });
throw new Error(`HTTP request failed: ${res.status} ${res.statusText}`);
}
if (!res.ok) {
console.error({ res, query, variables, headers });
throw new Error(`HTTP request failed: ${res.status} ${res.statusText}`);
}

const json = await res.json();
const json = await res.json();

if (json.errors) {
console.error({
query,
variables,
headers,
errors: json.errors,
});
throw json;
}
if (json.errors) {
console.error({
query,
variables,
headers,
errors: json.errors,
});
throw json;
}

return json.data;
};
return json.data;
},
);

export async function fetchApi<TData>(
query: string,
Expand Down
14 changes: 10 additions & 4 deletions src/lib/manageAsyncFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,22 @@ interface PromiseWrapperOptions {
throttleIntervalMs?: number;
timeoutMs?: number;
retries?: number;
retryMinTimeoutMs?: number;
}

const DEFAULT_OPTIONS: Required<PromiseWrapperOptions> = {
concurrencyLimit: 1,
throttleLimit: 10,
throttleLimit: 3,
throttleIntervalMs: 1000,
timeoutMs: 5000,
retries: 3,
timeoutMs: 7000,
retries: 4,
retryMinTimeoutMs: 2000,
};

type ManagedAsyncFunction<T extends (...args: unknown[]) => Promise<unknown>> =
(...args: Parameters<T>) => ClearablePromise<Awaited<ReturnType<T>>>;
<R extends Awaited<ReturnType<T>>>(
...args: Parameters<T>
) => ClearablePromise<R>;

export function manageAsyncFunction<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -46,6 +50,8 @@ export function manageAsyncFunction<
const retriedFn = (...args: Parameters<T>) =>
pRetry(() => timedFn(...args), {
retries: opts.retries,
minTimeout: opts.retryMinTimeoutMs,
randomize: true,
onFailedAttempt: (error) => {
console.log(
`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`,
Expand Down
30 changes: 14 additions & 16 deletions src/services/fcbh/getResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@ import { manageAsyncFunction } from '~src/lib/manageAsyncFunction';
const API_URL = 'https://4.dbt.io/api';
const API_KEY = process.env.BIBLE_BRAIN_KEY;

const doFetch = manageAsyncFunction((route: string) =>
fetch(`${API_URL}${route}&v=4&key=${API_KEY}`, {
method: 'GET',
}),
);
const getResponse = manageAsyncFunction(
async <T extends Record<string, unknown>>(route: string): Promise<T> => {
const result = await fetch(`${API_URL}${route}&v=4&key=${API_KEY}`, {
method: 'GET',
});

export default async function getResponse<T extends Record<string, unknown>>(
route: string,
): Promise<T> {
const result = await doFetch(route);
if (!result.ok) {
throw new Error(
`FCBH request failed: ${result.status} ${result.statusText}`,
);
}

if (!result.ok) {
throw new Error(
`FCBH request failed: ${result.status} ${result.statusText}`,
);
}
return result.json();
},
);

return result.json();
}
export default getResponse;

0 comments on commit 1fcec2f

Please sign in to comment.