Created
July 18, 2021 22:53
-
-
Save bagus2x/90c22049666da247d19d46bdb31dd3e6 to your computer and use it in GitHub Desktop.
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, { AxiosError, AxiosRequestConfig, AxiosResponse, CancelToken } from 'axios'; | |
| import { history } from '../App'; | |
| const BASE_URL = 'http://localhost:8080'; | |
| export const publicClient = axios.create({ | |
| baseURL: BASE_URL | |
| }); | |
| export const privateClient = axios.create({ | |
| baseURL: BASE_URL | |
| }); | |
| let isRefreshing = false; | |
| let failedQueue: Array<{ resolve: (value: any) => void; reject: (reason: any) => void }> = []; | |
| const processQueue = (error: any, token = null) => { | |
| failedQueue.forEach((prom) => { | |
| if (error) { | |
| prom.reject(error); | |
| } else { | |
| prom.resolve(token); | |
| } | |
| }); | |
| failedQueue = []; | |
| }; | |
| privateClient.interceptors.request.use((request) => { | |
| request.headers['x-auth-token'] = localStorage.getItem('access'); | |
| return request; | |
| }); | |
| privateClient.interceptors.response.use( | |
| function (response) { | |
| return response; | |
| }, | |
| function (error) { | |
| const originalRequest = error.config; | |
| if (error.response.status === 401 && !originalRequest._retry) { | |
| if (isRefreshing) { | |
| return new Promise(function (resolve, reject) { | |
| failedQueue.push({ resolve, reject }); | |
| }) | |
| .then((token) => { | |
| originalRequest.headers['x-auth-token'] = token; | |
| return axios(originalRequest); | |
| }) | |
| .catch((err) => { | |
| return Promise.reject(err); | |
| }); | |
| } | |
| originalRequest._retry = true; | |
| isRefreshing = true; | |
| const token = localStorage.getItem('refresh'); | |
| return new Promise(function (resolve, reject) { | |
| publicClient | |
| .post('/refresh', { token }) | |
| .then(({ data }) => { | |
| localStorage.setItem('refresh', data.refresh); | |
| localStorage.setItem('access', data.access); | |
| publicClient.defaults.headers.common['x-auth-token'] = data.access; | |
| originalRequest.headers['x-auth-token'] = data.access; | |
| processQueue(null, data.access); | |
| resolve(axios(originalRequest)); | |
| }) | |
| .catch((err) => { | |
| alert('redirect') | |
| localStorage.removeItem('access'); | |
| localStorage.removeItem('refresh'); | |
| history.replace('/') | |
| processQueue(err, null); | |
| reject(err); | |
| }) | |
| .finally(() => { | |
| isRefreshing = false; | |
| }); | |
| }); | |
| } | |
| return Promise.reject(error); | |
| } | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment