Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support abort signal for fetch calls #161

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 13 additions & 26 deletions sdk/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,37 +46,24 @@ export const retryFetch = (
url: string,
fetchOptions: RequestInit,
retries: number = 3,
timeout: number = 10 // set an overall timeout for this function
timeoutMs: number = 10 // set an overall timeout for this function
): Promise<Response> => {
return new Promise((resolve, reject) => {
const retryWrapper = (n: number) => {
requestWrapper()
.then(res => resolve(res))
.catch(async err => {
if (n > 0) {
await delay(1000);
retryWrapper(--n);
} else {
reject(err);
}
});
};

const requestWrapper = (): Promise<Response> => {
return new Promise((resolve, reject) => {
let timeoutId: NodeJS.Timeout;
if (timeout) {
timeoutId = setTimeout(() => reject('error: timeout'), timeout);
fetch(url, {
...fetchOptions,
signal: AbortSignal.timeout(timeoutMs)
})
.then(res => resolve(res))
.catch(async err => {
if (n > 0) {
await delay(1000);
retryWrapper(--n);
} else {
reject(err);
}
return fetch(url, fetchOptions)
.then(res => resolve(res))
.catch(err => reject(err))
.finally(() => {
if (timeoutId) {
clearTimeout(timeoutId);
}
});
});

};

retryWrapper(retries);
Expand Down
Loading