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

fix: preserve configuration for custom instance #240

Merged
merged 1 commit into from
Nov 16, 2023
Merged
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
9 changes: 6 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ export type RaxConfig = {
*/
export function attach(instance?: AxiosInstance) {
instance = instance || axios;
return instance.interceptors.response.use(onFulfilled, onError);
return instance.interceptors.response.use(
onFulfilled,
async (error: AxiosError) => onError(instance!, error),
);
}

/**
Expand Down Expand Up @@ -165,7 +168,7 @@ function parseRetryAfter(header: string): number | undefined {
return undefined;
}

async function onError(error: AxiosError) {
async function onError(instance: AxiosInstance, error: AxiosError) {
if (isCancel(error)) {
throw error;
}
Expand All @@ -175,7 +178,7 @@ async function onError(error: AxiosError) {
config.retry = typeof config.retry === 'number' ? config.retry : 3;
config.retryDelay =
typeof config.retryDelay === 'number' ? config.retryDelay : 100;
config.instance = config.instance || axios;
config.instance = config.instance || instance;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think config.instance can be deprecated following this change.

config.backoffType = config.backoffType || 'exponential';
config.httpMethodsToRetry = normalizeArray(config.httpMethodsToRetry) || [
'GET',
Expand Down
16 changes: 16 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,22 @@ describe('retry-axios', () => {
}
});

it('should retry at least the configured number of times for custom client', async function () {
this.timeout(10_000);
const scopes = [
nock(url).get('/').times(3).reply(500),
nock(url).get('/').reply(200, 'milk'),
];
const client = axios.create();
interceptorId = rax.attach(client);
const cfg: rax.RaxConfig = {url, raxConfig: {retry: 4}};
const result = await client(cfg);
assert.strictEqual(result.data, 'milk');
for (const s of scopes) {
s.done();
}
});

it('should not retry more than configured', async () => {
const scope = nock(url).get('/').twice().reply(500);
interceptorId = rax.attach();
Expand Down