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 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
191 changes: 191 additions & 0 deletions spec/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,197 @@ 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!');

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

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

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

client.get('http://example.com/test').then((result) => {
expect(result.status).toBe(200);
expect(anotherInterceptorBeforeFulfilledCallCount).toBe(1);
expect(anotherInterceptorBeforeRejectedCallCount).toBe(1);
expect(anotherInterceptorAfterFulfilledCallCount).toBe(1);
expect(anotherInterceptorAfterRejectedCallCount).toBe(0);
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!');

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

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

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

client.get('http://example.com/test').then((result) => {
expect(result.status).toBe(200);
expect(anotherInterceptorBeforeFulfilledCallCount).toBe(1);
expect(anotherInterceptorBeforeRejectedCallCount).toBe(2);
expect(anotherInterceptorAfterFulfilledCallCount).toBe(3);
expect(anotherInterceptorAfterRejectedCallCount).toBe(0);
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? :)


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

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

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

client
.get('http://example.com/test')
.then(
() => done.fail(),
(error) => {
expect(anotherInterceptorBeforeFulfilledCallCount).toBe(0);
expect(anotherInterceptorBeforeRejectedCallCount).toBe(1);
expect(anotherInterceptorAfterFulfilledCallCount).toBe(0);
expect(anotherInterceptorAfterRejectedCallCount).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);

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

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

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

client
.get('http://example.com/test')
.then(
() => done.fail(),
(error) => {
expect(anotherInterceptorBeforeFulfilledCallCount).toBe(0);
expect(anotherInterceptorBeforeRejectedCallCount).toBe(4);
expect(anotherInterceptorAfterFulfilledCallCount).toBe(0);
expect(anotherInterceptorAfterRejectedCallCount).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
46 changes: 43 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,23 @@ 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 interceptors = responseInterceptors.handlers.splice(0, responseInterceptorId + 1);

// Disable only intercepter on rejected (do not disable fullfilled)
responseInterceptors.handlers = interceptors.map((v, index) => {
if (index === responseInterceptorId) return v;
return { ...v, rejected: null };
});

resolve(axiosInstance(config));
return;
}
resolve(axiosInstance(config));
}, delay);
});
Comment on lines +254 to +270
Copy link

Choose a reason for hiding this comment

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

@yutak23 Thanks for your input!

I tested your solution under all test cases we have at the moment I created issue #246 – all passed 🎉

Unfortunately, we have received more production cases and updated our patch. Our previous version was not working properly with API client contest requests. Your solution appears to make the same mistake by detaching interceptors from the global client.

Here is seq diagram, to represent this simple contest use-case

image

The main change we made was to clone (dirty) the Axios client, so the global detachment of handlers won't affect contest requests through the same client.

Our new patch looks like this:

diff --git a/node_modules/axios-retry/lib/cjs/index.js b/node_modules/axios-retry/lib/cjs/index.js
index 1cfaeed..3dbc698 100644
--- a/node_modules/axios-retry/lib/cjs/index.js
+++ b/node_modules/axios-retry/lib/cjs/index.js
@@ -335,10 +335,17 @@ function axiosRetry(axios, defaultOptions) {
               config.transformRequest = [function (data) {
                 return data;
               }];
+
               onRetry(currentState.retryCount, error, config);
               return _context.abrupt("return", new Promise(function (resolve) {
                 return setTimeout(function () {
-                  return resolve(axios(config));
+                  var newClient = axios.create();
+
+                  var retryInterceptors = axios.interceptors.response.handlers[responseInterceptorId];
+
+                  newClient.interceptors.response = [retryInterceptors];
+
+                  return resolve(newClient(config));
                 }, delay);
               }));
 

We don't use custom interceptors before axios-retry so far, so your solution is more solid, and still looks better.
But could you confirm that your solution overcome this issue by providing new test cases?

}
return Promise.reject(error);
Expand Down
Loading