Created
July 28, 2022 15:52
-
-
Save afraser/bdc06dad58f91d3ffed595bb8e56d0a4 to your computer and use it in GitHub Desktop.
Axios api wrapper using CancelTokenSource (Deprecated - see https://axios-http.com/docs/cancellation)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { CancelTokenSource } from 'axios' | |
import TokenService from './token.service' | |
export const api = axios.create({ | |
baseURL: process.env.REACT_APP_API_BASE_URL || '', | |
withCredentials: true, | |
}) | |
const requestCancelSourcesByKey: { [cancelKey: string]: CancelTokenSource } = {} | |
export const cancelRequest = (cancelKey: string) => { | |
const cancelSource = requestCancelSourcesByKey[cancelKey] | |
if (cancelSource) { | |
cancelSource.cancel() | |
delete requestCancelSourcesByKey[cancelKey] | |
} | |
} | |
api.interceptors.request.use( | |
(config: any) => { | |
if (config.cancelKey) { | |
cancelRequest(config.cancelKey) | |
const newCancelSource = axios.CancelToken.source() | |
requestCancelSourcesByKey[config.cancelKey] = newCancelSource | |
config.cancelToken = newCancelSource.token | |
} | |
config.headers.Authorization = `Bearer ${TokenService.getAccess()}` | |
return config | |
}, | |
(error: Error) => { | |
return Promise.reject(error) | |
} | |
) | |
api.interceptors.response.use( | |
(response) => response, | |
async function (error) { | |
const originalReq = error.config | |
// invalid login | |
// do not want to make a request for refresh token | |
if (error.response?.status === 401 && originalReq.url === '/auth/sign_in') { | |
TokenService.remove() | |
return Promise.reject(error) | |
} | |
if (error.response?.status === 401 && originalReq.url !== '/auth/refresh_token' && !originalReq.isRetry) { | |
try { | |
originalReq.isRetry = true | |
await TokenService.refreshAccess() | |
return api.request(originalReq) | |
} catch (error: any) { | |
if (error.response?.status === 401) { | |
// clear tokens, force logout | |
TokenService.remove() | |
window.location.reload() | |
} | |
throw error | |
} | |
} else { | |
return Promise.reject(error) | |
} | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment