From d6d63731437aeefbd9150291cce568a365a74765 Mon Sep 17 00:00:00 2001 From: Orgad Shaneh Date: Thu, 16 Nov 2023 15:37:01 +0200 Subject: [PATCH] fix: preserve configuration for custom instance Fixes #68. --- src/index.ts | 9 ++++++--- test/index.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index e367dde..3f370ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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), + ); } /** @@ -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; } @@ -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', diff --git a/test/index.ts b/test/index.ts index 85c2f6d..24f397e 100644 --- a/test/index.ts +++ b/test/index.ts @@ -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();