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

fix: export the shouldRetryRequest method #74

Merged
merged 11 commits into from
Oct 23, 2020
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,26 @@ const res = await axios({
});
```

If you want to add custom retry logic without duplicating too much of the built-in logic, `rax.shouldRetryRequest` will tell you if a request would normally be retried:
```js
const res = await axios({
url: 'https://test.local',
raxConfig: {
// Override the decision making process on if you should retry
shouldRetry: err => {
const cfg = rax.getConfig(err);
if (cfg.currentRetryAttempt >= cfg.retry) return false // ensure max retries is always respected

// Always retry this status text, regardless of code or request type
if (err.response.statusText.includes('Try again')) return true

// Handle the request based on your other config options, e.g. `statusCodesToRetry`
return rax.shouldRetryRequest(err)
}
}
});
```

## How it works

This library attaches an `interceptor` to an axios instance you pass to the API. This way you get to choose which version of `axios` you want to run, and you can compose many interceptors on the same request pipeline.
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ function onError(err: AxiosError) {
* Determine based on config if we should retry the request.
* @param err The AxiosError passed to the interceptor.
*/
function shouldRetryRequest(err: AxiosError) {
export function shouldRetryRequest(err: AxiosError) {
const config = (err.config as RaxConfig).raxConfig;

// If there's no config, or retries are disabled, return.
Expand Down
6 changes: 1 addition & 5 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,7 @@ describe('retry-axios', () => {
for (const method of config!.httpMethodsToRetry!) {
assert(expectedMethods.indexOf(method) > -1, 'exected method: $method');
}
const expectedStatusCodes = [
[100, 199],
[429, 429],
[500, 599],
];
const expectedStatusCodes = [[100, 199], [429, 429], [500, 599]];
const statusCodesToRetry = config!.statusCodesToRetry!;
for (let i = 0; i < statusCodesToRetry.length; i++) {
const [min, max] = statusCodesToRetry[i];
Expand Down