Last active
May 18, 2022 03:16
-
-
Save SamiAlsubhi/3bf6cc5468f39547d57d2035b93e4f55 to your computer and use it in GitHub Desktop.
This file contains 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, {AxiosRequestConfig} from "axios"; | |
import axiosLock from "./axiosLock"; | |
const baseAxios = axios.create(); | |
const attachHeaders = (request: AxiosRequestConfig): AxiosRequestConfig => { | |
//attach auth headers to requests | |
const accessToken = localStorage.getItem("accessToken"); | |
if (accessToken) { | |
request.headers["Authorization"] = `Bearer ${accessToken}`; | |
} | |
return request | |
} | |
const refreshToken = async () Promise<boolean> =>{ | |
//IMPORTANT here you use a new axios instance or an instance created specifically for auth | |
//and does not have these interceptors | |
//refresh token and store the new token in localstorage | |
//return true of successfull | |
} | |
//lock requests | |
baseAxios.interceptors.request.use(async (request) => { | |
if (axiosLock.isLocked) { | |
await axiosLock.waitForUnlock(); | |
} | |
return attachHeaders(request) | |
}) | |
//Refresh token interceptors | |
baseAxios.interceptors.response.use( | |
(response) => { | |
return response; | |
}, | |
async (error) => { | |
const originalRequest = error.config; | |
//check if the request was not cancelled | |
if (axios.isCancel(error)) { | |
return Promise.reject(error); | |
} | |
//check if the status code is 401 | |
if (error.response.status !== 401) { | |
return Promise.reject(error); | |
} | |
//check if axios is locked | |
if (axiosLock.isLocked) { | |
await apiLock.waitForUnlock() | |
return axios(attachHeaders(originalRequest)) | |
} | |
//try to refresh the access_token | |
axiosLock.lock() | |
if (await refreshToken()) { | |
axiosLock.unlock() | |
return axios(attachHeaders(originalRequest)); | |
} | |
axiosLock.unlock() | |
return Promise.reject(error); | |
} | |
) | |
export default baseAxios |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment