Skip to content

Commit

Permalink
fix: preserve configuration for custom instance (#240)
Browse files Browse the repository at this point in the history
Fixes #68.
  • Loading branch information
orgads authored Nov 16, 2023
1 parent 731edbf commit 2e4e702
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
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;
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

0 comments on commit 2e4e702

Please sign in to comment.