feat: request queue
This commit is contained in:
parent
4fc9ec59c8
commit
b9dee09060
1 changed files with 28 additions and 1 deletions
|
|
@ -1,10 +1,16 @@
|
||||||
import axios, { AxiosInstance } from 'axios';
|
import axios, { AxiosError, AxiosInstance } from 'axios';
|
||||||
|
|
||||||
import { AppError } from '@utils/AppError';
|
import { AppError } from '@utils/AppError';
|
||||||
|
|
||||||
import { storageAuthTokenGet } from '@storage/storageAuthToken';
|
import { storageAuthTokenGet } from '@storage/storageAuthToken';
|
||||||
|
|
||||||
type SignOut = () => void;
|
type SignOut = () => void;
|
||||||
|
|
||||||
|
type PromiseType = {
|
||||||
|
onSuccess: (token: string) => void;
|
||||||
|
onFailure: (error: AxiosError) => void;
|
||||||
|
};
|
||||||
|
|
||||||
type APIInstanceProps = AxiosInstance & {
|
type APIInstanceProps = AxiosInstance & {
|
||||||
registerInterceptTokenManager: (signOut: SignOut) => () => void;
|
registerInterceptTokenManager: (signOut: SignOut) => () => void;
|
||||||
};
|
};
|
||||||
|
|
@ -22,6 +28,9 @@ api.interceptors.request.use(
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let failedQueue: Array<PromiseType> = [];
|
||||||
|
let isRefreshing = false;
|
||||||
|
|
||||||
api.registerInterceptTokenManager = (signOut: SignOut) => {
|
api.registerInterceptTokenManager = (signOut: SignOut) => {
|
||||||
const interceptTokenManager = api.interceptors.response.use(
|
const interceptTokenManager = api.interceptors.response.use(
|
||||||
(response) => response,
|
(response) => response,
|
||||||
|
|
@ -37,6 +46,24 @@ api.registerInterceptTokenManager = (signOut: SignOut) => {
|
||||||
signOut();
|
signOut();
|
||||||
return Promise.reject(requestError);
|
return Promise.reject(requestError);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const originalRequestConfig = requestError.config;
|
||||||
|
|
||||||
|
if (isRefreshing) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
failedQueue.push({
|
||||||
|
onSuccess: (token: string) => {
|
||||||
|
originalRequestConfig.headers.Authorization = `Bearer ${token}`;
|
||||||
|
resolve(api(originalRequestConfig));
|
||||||
|
},
|
||||||
|
onFailure: (error: AxiosError) => {
|
||||||
|
reject(error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
isRefreshing = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
signOut();
|
signOut();
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue