Skip to content

Commit

Permalink
feat(api): New config option maxRetries (default 3) to retry on 429…
Browse files Browse the repository at this point in the history
… and 5xx errors

Handles `retry-after` (ms) rate limit response header
  • Loading branch information
leomp12 committed Jun 16, 2022
1 parent d4b8190 commit 35c5287
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
20 changes: 17 additions & 3 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,17 @@ const setMiddleware = (middleware: typeof def.middleware) => {
def.middleware = middleware;
};

const api = async <T extends Config>(config: T): Promise<Response & {
const api = async <T extends Config>(config: T, retries = 0): Promise<Response & {
config: Config,
data: ResponseBody<T>,
}> => {
const url = def.middleware(config);
const { method, headers, timeout = 20000 } = config;
const {
method,
headers,
timeout = 20000,
maxRetries = 3,
} = config;
const abortController = new AbortController();
const timer = setTimeout(() => abortController.abort(), timeout);
const response = await fetch(url, {
Expand All @@ -55,10 +60,19 @@ const api = async <T extends Config>(config: T): Promise<Response & {
data: await response.json(),
};
}
const { status } = response;
if (maxRetries < retries && (status === 429 || status >= 500)) {
const retryAfter = response.headers.get('retry-after');
return new Promise((resolve, reject) => {
setTimeout(() => {
api(config, retries + 1).then(resolve).catch(reject);
}, (retryAfter && parseInt(retryAfter, 10)) || 5000);
});
}
const error: any = new Error(response.statusText);
error.config = config;
error.response = response;
error.statusCode = response.status;
error.statusCode = status;
throw error;
};

Expand Down
1 change: 1 addition & 0 deletions packages/api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type Config = {
params?: Record<string, string | number>,
headers?: Record<string, string>,
timeout?: number,
maxRetries?: number,
};

type ReadConfig<endpoint> = Config & { method?: 'get', endpoint: endpoint };
Expand Down

0 comments on commit 35c5287

Please sign in to comment.