Skip to content
This repository has been archived by the owner on Feb 12, 2022. It is now read-only.

Commit

Permalink
retry when http status is 429 as well, respect the Retry-After header
Browse files Browse the repository at this point in the history
  • Loading branch information
nkzawa committed Feb 26, 2020
1 parent 6584649 commit 9818691
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ function setup(fetch) {
// this will be retried
const res = await fetch(url, opts);
debug('status %d', res.status);
if (res.status >= 500 && res.status < 600) {
if ((res.status >= 500 && res.status < 600) || res.status === 429) {
// NOTE: doesn't support http-date format
const retryAfter = parseInt(res.headers.get('retry-after'), 10);
if (retryAfter) {
await new Promise(r => setTimeout(r, retryAfter * 1e3));
}
throw new ResponseError(res);
} else {
return res;
Expand Down
29 changes: 29 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,32 @@ test('accepts a custom onRetry option', async () => {
server.on('error', reject);
});
})

test('handle the Retry-After header', async () => {
const server = createServer((req, res) => {
res.writeHead(429, { 'Retry-After': 1 });
res.end();
});

return new Promise((resolve, reject) => {
server.listen(async () => {
const {port} = server.address();
try {
const startedAt = Date.now();
const res = await retryFetch(`http://127.0.0.1:${port}`, {
retry: {
minTimeout: 10,
retries: 1
}
});
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(1010);
resolve();
} catch (err) {
reject(err);
} finally {
server.close();
}
});
server.on('error', reject);
});
});

0 comments on commit 9818691

Please sign in to comment.