@@ -11,6 +11,8 @@ import {
1111} from '@/utils' ;
1212import { handleRefreshToken } from './helpers' ;
1313
14+ type RefreshRequestQueue = ( config : AxiosRequestConfig ) => void ;
15+
1416/**
1517 * 封装axios请求类
1618 * @author Soybean<honghuangdc@gmail.com>
@@ -20,6 +22,10 @@ export default class CustomAxiosInstance {
2022
2123 backendConfig : Service . BackendResultConfig ;
2224
25+ isRefreshing : boolean ;
26+
27+ retryQueues : RefreshRequestQueue [ ] ;
28+
2329 /**
2430 *
2531 * @param axiosConfig - axios配置
@@ -37,6 +43,8 @@ export default class CustomAxiosInstance {
3743 this . backendConfig = backendConfig ;
3844 this . instance = axios . create ( axiosConfig ) ;
3945 this . setInterceptor ( ) ;
46+ this . isRefreshing = false ;
47+ this . retryQueues = [ ] ;
4048 }
4149
4250 /** 设置请求拦截器 */
@@ -60,7 +68,7 @@ export default class CustomAxiosInstance {
6068 ) ;
6169 this . instance . interceptors . response . use (
6270 ( async response => {
63- const { status } = response ;
71+ const { status, config } = response ;
6472 if ( status === 200 || status < 300 || status === 304 ) {
6573 const backend = response . data ;
6674 const { codeKey, dataKey, successCode } = this . backendConfig ;
@@ -71,10 +79,24 @@ export default class CustomAxiosInstance {
7179
7280 // token失效, 刷新token
7381 if ( REFRESH_TOKEN_CODE . includes ( backend [ codeKey ] ) ) {
74- const config = await handleRefreshToken ( response . config ) ;
75- if ( config ) {
76- return this . instance . request ( config ) ;
82+ // 原始请求
83+ const originRequest = new Promise ( resolve => {
84+ this . retryQueues . push ( ( refreshConfig : AxiosRequestConfig ) => {
85+ config . headers . Authorization = refreshConfig . headers ?. Authorization ;
86+ resolve ( this . instance . request ( config ) ) ;
87+ } ) ;
88+ } ) ;
89+
90+ if ( ! this . isRefreshing ) {
91+ this . isRefreshing = true ;
92+ const refreshConfig = await handleRefreshToken ( response . config ) ;
93+ if ( refreshConfig ) {
94+ this . retryQueues . map ( cb => cb ( refreshConfig ) ) ;
95+ }
96+ this . retryQueues = [ ] ;
97+ this . isRefreshing = false ;
7798 }
99+ return originRequest ;
78100 }
79101
80102 const error = handleBackendError ( backend , this . backendConfig ) ;
0 commit comments