Skip to content

Commit

Permalink
Support passing function for axios client delay (#270)
Browse files Browse the repository at this point in the history
  • Loading branch information
chalenge authored Jun 24, 2024
1 parent ecddcc8 commit 98e5e1a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions src/axios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {Logger} from 'pino';

import {wrapApiError} from './errors';

type DelayFunction = (error: AxiosError<unknown, any>) => number;

export const DEFAULT_RETRIES = 3;
export const DEFAULT_RETRY_DELAY = 1000;

Expand All @@ -30,7 +32,7 @@ export function makeAxiosInstanceWithRetry(
config?: AxiosRequestConfig,
logger?: Logger<string>,
retries = DEFAULT_RETRIES,
delay = DEFAULT_RETRY_DELAY
delay: number | DelayFunction = DEFAULT_RETRY_DELAY
): AxiosInstance {
const isNetworkError = (error: AxiosError<any>): boolean => {
return (
Expand Down Expand Up @@ -60,7 +62,11 @@ export function makeAxiosInstanceWithRetry(
wrapApiError(error, `Retry attempt ${retryNumber} of ${retries}`)
);
}
return retryNumber * delay;
if (typeof delay === 'number') {
return retryNumber * delay;
}
return delay(error);

},
shouldResetTimeout: true,
});
Expand Down
16 changes: 16 additions & 0 deletions test/axios.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,20 @@ describe('axios', () => {
);
mock.done();
});

test('delay using function', async () => {
const mock = mockPostCode('/hi', 502);
const client = sut.makeAxiosInstanceWithRetry(
{baseURL: apiUrl},
undefined,
3,
() => {
return 50;
}
);
const res = await client.post('/hi');
expect(res.status).toBe(200);
expect(res.data).toStrictEqual({tenantId: '1'});
mock.done();
});
});

0 comments on commit 98e5e1a

Please sign in to comment.