Skip to content

Commit

Permalink
Added support for axios abort signal
Browse files Browse the repository at this point in the history
  • Loading branch information
michal-billtech committed Jun 4, 2024
1 parent 703df66 commit dbc563c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
28 changes: 27 additions & 1 deletion spec/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import http from 'http';
import nock from 'nock';
import axios, { AxiosError, isAxiosError } from 'axios';
import axios, { AxiosError, CanceledError, isAxiosError } from 'axios';
import axiosRetry, {
isNetworkError,
isSafeRequestError,
Expand Down Expand Up @@ -326,6 +326,32 @@ describe('axiosRetry(axios, { retries, retryCondition })', () => {
.catch(done.fail);
});
});

describe('when request is aborted', () => {
it('should clearTimeout', (done) => {
const client = axios.create({
timeout: 100000
});
setupResponses(client, [() => nock('http://example.com').get('/test').reply(429)]);
axiosRetry(client, {
retries: 1,
retryCondition: () => true,
retryDelay: () => 9999999
});
const abortController = new AbortController();
client
.get('http://example.com/test', { signal: abortController.signal })
.then(
() => done.fail(),
(error) => {
expect(error).toBeInstanceOf(CanceledError);
done();
}
)
.catch(done.fail);
abortController.abort();
});
});
});

describe('when it does NOT satisfy the retry condition', () => {
Expand Down
11 changes: 10 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,16 @@ async function handleRetry(
config.transformRequest = [(data) => data];
await onRetry(currentState.retryCount, error, config);
return new Promise((resolve) => {
setTimeout(() => resolve(axiosInstance(config)), delay);
const timeout = setTimeout(() => resolve(axiosInstance(config)), delay);
if (config.signal?.addEventListener) {
config.signal.addEventListener(
'abort',
() => {
clearTimeout(timeout);
},
{ once: true }
);
}
});
}

Expand Down

0 comments on commit dbc563c

Please sign in to comment.