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

Support passing function for axios client delay #270

Merged
merged 2 commits into from
Jun 24, 2024
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
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();
});
});
Loading