mirror of
https://github.com/monkeytypegame/monkeytype.git
synced 2024-11-11 18:03:30 +08:00
Add retry utility for ape (#3548) Bruception
This commit is contained in:
parent
894b4f53bf
commit
8f9dc3d7c9
1 changed files with 53 additions and 0 deletions
53
frontend/src/ts/ape/utils.ts
Normal file
53
frontend/src/ts/ape/utils.ts
Normal file
|
@ -0,0 +1,53 @@
|
|||
type ShouldRetryCallback = (
|
||||
statusCode: number,
|
||||
response?: Ape.HttpClientResponse
|
||||
) => boolean;
|
||||
|
||||
interface RetryOptions {
|
||||
shouldRetry?: ShouldRetryCallback;
|
||||
retryAttempts?: number;
|
||||
retryDelayMs?: number;
|
||||
}
|
||||
|
||||
const wait = (delay: number): Promise<number> =>
|
||||
new Promise((resolve) => window.setTimeout(resolve, delay));
|
||||
|
||||
const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
|
||||
shouldRetry: (statusCode: number): boolean =>
|
||||
statusCode >= 500 && statusCode !== 503,
|
||||
retryAttempts: 3,
|
||||
retryDelayMs: 3000,
|
||||
};
|
||||
|
||||
export async function withRetry(
|
||||
fn: () => Ape.EndpointData,
|
||||
opts?: RetryOptions
|
||||
): Ape.EndpointData {
|
||||
const retry = async (
|
||||
previousData: Ape.HttpClientResponse,
|
||||
completeOpts: Required<RetryOptions>
|
||||
): Promise<Ape.HttpClientResponse> => {
|
||||
const { retryAttempts, shouldRetry, retryDelayMs } = completeOpts;
|
||||
|
||||
if (retryAttempts <= 0 || !shouldRetry(previousData.status, previousData)) {
|
||||
return previousData;
|
||||
}
|
||||
|
||||
const data = await fn();
|
||||
const { status } = data;
|
||||
|
||||
if (shouldRetry(status, data)) {
|
||||
await wait(retryDelayMs);
|
||||
|
||||
--completeOpts.retryAttempts;
|
||||
return await retry(data, completeOpts);
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
return await retry(await fn(), {
|
||||
...DEFAULT_RETRY_OPTIONS,
|
||||
...opts,
|
||||
});
|
||||
}
|
Loading…
Reference in a new issue