From 0eaa327d471e9c34d671e8e7c2bd9b2c97ba7c36 Mon Sep 17 00:00:00 2001 From: liwei Date: Thu, 13 Jul 2023 21:34:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E9=98=B2=E6=AD=A2=E5=A4=9A?= =?UTF-8?q?=E6=AC=A1=E5=88=B7=E6=96=B0token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/service/request/instance.ts | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/service/request/instance.ts b/src/service/request/instance.ts index 04fb26ca..d625927f 100644 --- a/src/service/request/instance.ts +++ b/src/service/request/instance.ts @@ -11,6 +11,8 @@ import { } from '@/utils'; import { handleRefreshToken } from './helpers'; +type RefreshRequestQueue = (config: AxiosRequestConfig) => void; + /** * 封装axios请求类 * @author Soybean @@ -20,6 +22,10 @@ export default class CustomAxiosInstance { backendConfig: Service.BackendResultConfig; + isRefreshing: boolean; + + retryQueues: RefreshRequestQueue[]; + /** * * @param axiosConfig - axios配置 @@ -37,6 +43,8 @@ export default class CustomAxiosInstance { this.backendConfig = backendConfig; this.instance = axios.create(axiosConfig); this.setInterceptor(); + this.isRefreshing = false; + this.retryQueues = []; } /** 设置请求拦截器 */ @@ -60,7 +68,7 @@ export default class CustomAxiosInstance { ); this.instance.interceptors.response.use( (async response => { - const { status } = response; + const { status, config } = response; if (status === 200 || status < 300 || status === 304) { const backend = response.data; const { codeKey, dataKey, successCode } = this.backendConfig; @@ -71,10 +79,24 @@ export default class CustomAxiosInstance { // token失效, 刷新token if (REFRESH_TOKEN_CODE.includes(backend[codeKey])) { - const config = await handleRefreshToken(response.config); - if (config) { - return this.instance.request(config); + // 原始请求 + const originRequest = new Promise(resolve => { + this.retryQueues.push((refreshConfig: AxiosRequestConfig) => { + config.headers.Authorization = refreshConfig.headers?.Authorization; + resolve(this.instance.request(config)); + }); + }); + + if (!this.isRefreshing) { + this.isRefreshing = true; + const refreshConfig = await handleRefreshToken(response.config); + if (refreshConfig) { + this.retryQueues.map(cb => cb(refreshConfig)); + } + this.retryQueues = []; + this.isRefreshing = false; } + return originRequest; } const error = handleBackendError(backend, this.backendConfig);