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: add disableOtherResponseInterceptors option #260

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
99 changes: 99 additions & 0 deletions spec/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,105 @@ describe('axiosRetry(axios, { retries, onRetry })', () => {
});
});

describe('axiosRetry(axios, { disableOtherResponseInterceptors })', () => {
afterEach(() => {
nock.cleanAll();
nock.enableNetConnect();
});

describe('successful after retry', () => {
it('should not multiple response interceptor', (done) => {
const client = axios.create();
nock('http://example.com').get('/test').times(2).replyWithError(NETWORK_ERROR);
nock('http://example.com').get('/test').reply(200, 'It worked!');

axiosRetry(client, { retries: 3, disableOtherResponseInterceptors: true });

let anotherInterceptorCallCount = 0;
client.interceptors.response.use((result) => {
anotherInterceptorCallCount += 1;
return result;
}, null);

client.get('http://example.com/test').then((result) => {
expect(result.status).toBe(200);
expect(anotherInterceptorCallCount).toBe(1);
done();
}, done.fail);
});

it('should multiple response interceptor', (done) => {
const client = axios.create();
nock('http://example.com').get('/test').times(2).replyWithError(NETWORK_ERROR);
nock('http://example.com').get('/test').reply(200, 'It worked!');

axiosRetry(client, { retries: 3, disableOtherResponseInterceptors: false });

let anotherInterceptorCallCount = 0;
client.interceptors.response.use((result) => {
anotherInterceptorCallCount += 1;
return result;
}, null);

client.get('http://example.com/test').then((result) => {
expect(result.status).toBe(200);
expect(anotherInterceptorCallCount).toBe(3);
done();
}, done.fail);
});
});

describe('failure after retry', () => {
it('should not multiple response interceptor', (done) => {
const client = axios.create();
nock('http://example.com').get('/test').times(3).replyWithError(NETWORK_ERROR);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
nock('http://example.com').get('/test').times(3).replyWithError(NETWORK_ERROR);
nock('http://example.com').get('/test').times(3).replyWithError(NETWORK_ERROR);
nock('http://example.com').get('/test').reply(200, 'It worked!');

I assumed that adding this line here wouldn't affect test results, but it did. Am I mistaken? :)


axiosRetry(client, { retries: 3, disableOtherResponseInterceptors: true });

let anotherInterceptorCallCount = 0;
client.interceptors.response.use(null, (error) => {
anotherInterceptorCallCount += 1;
return Promise.reject(error);
});

client
.get('http://example.com/test')
.then(
() => done.fail(),
(error) => {
expect(anotherInterceptorCallCount).toBe(1);
done();
}
)
.catch(done.fail);
});

it('should multiple response interceptor', (done) => {
const client = axios.create();
nock('http://example.com').get('/test').times(3).replyWithError(NETWORK_ERROR);

axiosRetry(client, { retries: 3, disableOtherResponseInterceptors: false });

let anotherInterceptorCallCount = 0;
client.interceptors.response.use(null, (error) => {
anotherInterceptorCallCount += 1;
return Promise.reject(error);
});

client
.get('http://example.com/test')
.then(
() => done.fail(),
(error) => {
expect(anotherInterceptorCallCount).toBe(4);
done();
}
)
.catch(done.fail);
});
});
});

describe('isNetworkError(error)', () => {
it('should be true for network errors like connection refused', () => {
const connectionRefusedError = new AxiosError();
Expand Down
40 changes: 37 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import type { AxiosError, AxiosRequestConfig, AxiosInstance, AxiosStatic } from 'axios';
import type {
AxiosError,
AxiosRequestConfig,
AxiosInstance,
AxiosStatic,
AxiosInterceptorManager,
AxiosResponse,
InternalAxiosRequestConfig
} from 'axios';
import isRetryAllowed from 'is-retry-allowed';

interface AxiosResponseInterceptorManagerExtended extends AxiosInterceptorManager<AxiosResponse> {
handlers: Array<{
Copy link
Contributor Author

@yutak23 yutak23 Dec 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a handlers property in the axios request/response interceptor, but it is not present in the current axios type definition. Therefore, we are extending it on our own.

However, if the following PRs are merged, this definition will no longer be necessary.
axios/axios#6138

But, it is not clear when the proposal will be adopted, so the axios-retry side would be quicker to merge first with this definition.

fulfilled: ((value: AxiosResponse) => AxiosResponse | Promise<AxiosResponse>) | null;
rejected: ((error: any) => any) | null;
synchronous: boolean;
runWhen: (config: InternalAxiosRequestConfig) => boolean | null;
}>;
}
Copy link
Contributor Author

@yutak23 yutak23 Dec 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have checked the following JavaScrip implementation on my end and defined the types.
https://github.com/axios/axios/blob/v1.6.2/lib/core/InterceptorManager.js#L23


export interface IAxiosRetryConfig {
/**
* The number of times to retry before failing
Expand All @@ -12,6 +29,11 @@ export interface IAxiosRetryConfig {
* default: false
*/
shouldResetTimeout?: boolean;
/**
* Disable other response interceptors when axios-retry is retrying the request
* default: false
*/
disableOtherResponseInterceptors?: boolean;
/**
* A callback to further control if a request should be retried.
* default: it retries if it is a network error or a 5xx error on an idempotent request (GET, HEAD, OPTIONS, PUT or DELETE).
Expand Down Expand Up @@ -141,6 +163,7 @@ export const DEFAULT_OPTIONS: Required<IAxiosRetryConfig> = {
retryCondition: isNetworkOrIdempotentRequestError,
retryDelay: noDelay,
shouldResetTimeout: false,
disableOtherResponseInterceptors: false,
onRetry: () => {}
};

Expand Down Expand Up @@ -196,13 +219,14 @@ async function shouldRetry(
return shouldRetryOrPromise;
}

let responseInterceptorId: number;
const axiosRetry: AxiosRetry = (axiosInstance, defaultOptions) => {
const requestInterceptorId = axiosInstance.interceptors.request.use((config) => {
setCurrentState(config, defaultOptions);
return config;
});

const responseInterceptorId = axiosInstance.interceptors.response.use(null, async (error) => {
responseInterceptorId = axiosInstance.interceptors.response.use(null, async (error) => {
const { config } = error;
// If we have no information to retry the request
if (!config) {
Expand All @@ -227,7 +251,17 @@ const axiosRetry: AxiosRetry = (axiosInstance, defaultOptions) => {
config.transformRequest = [(data) => data];
await onRetry(currentState.retryCount, error, config);
return new Promise((resolve) => {
setTimeout(() => resolve(axiosInstance(config)), delay);
setTimeout(() => {
if (currentState.disableOtherResponseInterceptors && currentState.retryCount === 1) {
const responseInterceptors = axiosInstance.interceptors
.response as AxiosResponseInterceptorManagerExtended;
const axiosRetryInterceptor = responseInterceptors.handlers[responseInterceptorId];
responseInterceptors.handlers = [axiosRetryInterceptor];
resolve(axiosInstance(config));
return;
}
resolve(axiosInstance(config));
}, delay);
});
}
return Promise.reject(error);
Expand Down
Loading