Skip to content

Commit 98e5e1a

Browse files
authored
Support passing function for axios client delay (#270)
1 parent ecddcc8 commit 98e5e1a

File tree

3 files changed

+31
-9
lines changed

3 files changed

+31
-9
lines changed

package-lock.json

Lines changed: 7 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/axios.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {Logger} from 'pino';
55

66
import {wrapApiError} from './errors';
77

8+
type DelayFunction = (error: AxiosError<unknown, any>) => number;
9+
810
export const DEFAULT_RETRIES = 3;
911
export const DEFAULT_RETRY_DELAY = 1000;
1012

@@ -30,7 +32,7 @@ export function makeAxiosInstanceWithRetry(
3032
config?: AxiosRequestConfig,
3133
logger?: Logger<string>,
3234
retries = DEFAULT_RETRIES,
33-
delay = DEFAULT_RETRY_DELAY
35+
delay: number | DelayFunction = DEFAULT_RETRY_DELAY
3436
): AxiosInstance {
3537
const isNetworkError = (error: AxiosError<any>): boolean => {
3638
return (
@@ -60,7 +62,11 @@ export function makeAxiosInstanceWithRetry(
6062
wrapApiError(error, `Retry attempt ${retryNumber} of ${retries}`)
6163
);
6264
}
63-
return retryNumber * delay;
65+
if (typeof delay === 'number') {
66+
return retryNumber * delay;
67+
}
68+
return delay(error);
69+
6470
},
6571
shouldResetTimeout: true,
6672
});

test/axios.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,20 @@ describe('axios', () => {
114114
);
115115
mock.done();
116116
});
117+
118+
test('delay using function', async () => {
119+
const mock = mockPostCode('/hi', 502);
120+
const client = sut.makeAxiosInstanceWithRetry(
121+
{baseURL: apiUrl},
122+
undefined,
123+
3,
124+
() => {
125+
return 50;
126+
}
127+
);
128+
const res = await client.post('/hi');
129+
expect(res.status).toBe(200);
130+
expect(res.data).toStrictEqual({tenantId: '1'});
131+
mock.done();
132+
});
117133
});

0 commit comments

Comments
 (0)