@@ -11,6 +11,8 @@ import {
11
11
} from '@/utils' ;
12
12
import { handleRefreshToken } from './helpers' ;
13
13
14
+ type RefreshRequestQueue = ( config : AxiosRequestConfig ) => void ;
15
+
14
16
/**
15
17
* 封装axios请求类
16
18
* @author Soybean<honghuangdc@gmail.com>
@@ -20,6 +22,10 @@ export default class CustomAxiosInstance {
20
22
21
23
backendConfig : Service . BackendResultConfig ;
22
24
25
+ isRefreshing : boolean ;
26
+
27
+ retryQueues : RefreshRequestQueue [ ] ;
28
+
23
29
/**
24
30
*
25
31
* @param axiosConfig - axios配置
@@ -37,6 +43,8 @@ export default class CustomAxiosInstance {
37
43
this . backendConfig = backendConfig ;
38
44
this . instance = axios . create ( axiosConfig ) ;
39
45
this . setInterceptor ( ) ;
46
+ this . isRefreshing = false ;
47
+ this . retryQueues = [ ] ;
40
48
}
41
49
42
50
/** 设置请求拦截器 */
@@ -60,7 +68,7 @@ export default class CustomAxiosInstance {
60
68
) ;
61
69
this . instance . interceptors . response . use (
62
70
( async response => {
63
- const { status } = response ;
71
+ const { status, config } = response ;
64
72
if ( status === 200 || status < 300 || status === 304 ) {
65
73
const backend = response . data ;
66
74
const { codeKey, dataKey, successCode } = this . backendConfig ;
@@ -71,10 +79,24 @@ export default class CustomAxiosInstance {
71
79
72
80
// token失效, 刷新token
73
81
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 ;
77
98
}
99
+ return originRequest ;
78
100
}
79
101
80
102
const error = handleBackendError ( backend , this . backendConfig ) ;
0 commit comments