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

Add interceptNetworkError to AxiosAuthRefreshOptions #134

Merged
merged 1 commit into from
Jan 12, 2021
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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@ This prevents interceptor from running for each failed request.
}
```

#### Intercept on network error

Some CORS APIs may not return CORS response headers when an HTTP 401 Unauthorized response is returned.
In this scenario, the browser won't be able to read the response headers to determine the response status code.

To intercept *any* network error, enable the `interceptNetworkError` option.

CAUTION: This should be used as a last resort. If this is used to work around an API that doesn't support CORS
with an HTTP 401 response, your retry logic can test for network connectivity attempting refresh authentication.

```javascript
{
interceptNetworkError: true // default: undefined
}
```

### Other usages of the library
This library has also been used for:

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface AxiosAuthRefreshOptions {
*/
skipWhileRefreshing?: boolean;
pauseInstanceWhileRefreshing?: boolean;
interceptNetworkError?: boolean;
onRetry?: (requestConfig: AxiosRequestConfig) => AxiosRequestConfig
}

Expand Down
12 changes: 11 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,20 @@ export function shouldInterceptError(
return false;
}

if (!error.response || !options.statusCodes.includes(parseInt(error.response.status))) {
if (
!(options.interceptNetworkError && !error.response && error.request.status === 0) &&
(!error.response || !options.statusCodes?.includes(parseInt(error.response.status)))
) {
return false;
}

// Copy config to response if there's a network error, so config can be modified and used in the retry
if (!error.response) {
error.response = {
config: error.config,
};
}

return !options.pauseInstanceWhileRefreshing || !cache.skipInstances.includes(instance);
}

Expand Down