center.ts
6.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { clearAuth, getToken } from "@/utils/auth";
import { localCache } from "@/utils/storage";
import { ElMessage } from "element-plus";
/**
* 配置中心管理
* 使用 fetch 解决 axios 提前实例化导致 sign 里面的 secret 不能通过配置中心动态获取
*/
import { Defaults, Request } from "glsk-toolkit";
import {
CONFIG_CACHE_KEY,
CONFIG_CENTER_URL as CONFIG_URL,
ROUTER_CONFIG_CACHE_KEY,
ROUTER_CONFIG_URL as ROUTER_URL,
} from "./constants"; // 导入常量配置
// 配置数据
// eslint-disable-next-line import/no-mutable-exports
let baseConfig: any = {};
// GSC API 请求实例(模块级单例,不挂载到 window)
let gscApiInstance: null | Request = null;
// 配置加载完成的 Promise
let configReadyPromise: null | Promise<void> = null;
let configReadyResolve: (() => void) | null = null;
/**
* @desc 与waitForConfigReady方法配套使用,
* @desc 用于创建一个“等待机制”(Promise)
* @desc 保存“完成通知按钮”(resolve 函数)
* @desc 让其他代码可以“等待配置加载完成”
*/
function initConfigReadyPromise() {
if (!configReadyPromise) {
configReadyPromise = new Promise<void>((resolve) => {
configReadyResolve = resolve;
});
}
// console.log('initConfigReadyPromise',configReadyPromise);
return configReadyPromise;
}
/**
* 获取远程路由配置数据
* @returns 路由数据
*/
export async function fetchMicroAppRouteConfig(): Promise<any> {
if (baseConfig.features.defaultRoute.enabled){
return {
"code": 200,
"message": "success",
"data": {
"microApps": [
{
"name": "home",
"entry": {
"development": "",
"production": "",
"test": "",
"default": ""
},
"container": "#subapp-viewport",
"activeRule": "/home",
"props": {
"routerBase": "/home"
},
"enabled": true,
"routes": {
"path": "/home",
"name": "Home",
"title": "首页",
"level": 1,
"isMicroApp": false,
"requiresAuth": true
},
"routerList": {
"id": "home",
"title": "首页",
"path": "/home",
"icon": "",
"sidebarMenus": [
{
"id": "home-dashboard",
"title": "工作台",
"path": "/home/dashboard",
"icon": "",
"level": 2,
"hidden": false,
"parentId": "home",
"meta": {
"title": "工作台",
"icon": "dashboard",
"noCache": false,
"link": null
},
"children": []
}
]
}
}
]
}
};
}
// 先检查本地缓存
const cachedData = localCache.get(ROUTER_CONFIG_CACHE_KEY);
if (cachedData) {
return cachedData;
}
// 缓存不存在,从远程获取
const response = await fetch(ROUTER_URL);
const result = await response.json();
// 保存到本地缓存
if (result) {
localCache.set(ROUTER_CONFIG_CACHE_KEY, result);
}
return result;
}
/**
* 获取 GSC API 请求实例
* @returns Request 实例,如果未初始化则返回 null
*/
export function getGscApi(): null | Request {
return gscApiInstance;
}
/**
* 等待配置加载完成
* @returns Promise<void>
*/
export function waitForConfigReady(): Promise<void> {
if (gscApiInstance) {
return Promise.resolve();
}
if (!configReadyPromise) {
initConfigReadyPromise();
}
return configReadyPromise || Promise.resolve();
}
/**
* 获取配置中心配置
* @returns Promise<配置数据>
*/
export async function fetchConfig(): Promise<any> {
// 初始化配置就绪 Promise
initConfigReadyPromise();
try {
// 先检查本地缓存
const cachedData = localCache.get(CONFIG_CACHE_KEY);
let configData: any;
if (cachedData) {
configData = cachedData;
} else {
// 缓存不存在,从远程获取
const response = await fetch(CONFIG_URL);
configData = await response.json();
// 保存到本地缓存
if (configData) {
localCache.set(CONFIG_CACHE_KEY, configData);
console.log("[配置中心] 基本配置已缓存到本地");
}
}
baseConfig = configData;
window.$fetchConfig = configData;
// 统一初始化 GSC API(无论 code 是什么,只要有配置就初始化)
const gscConfig = configData?.gsc || configData;
if (gscConfig){
// 创建全局默认配置
const globalDefaults = new Defaults({
...gscConfig,
events: {
error: (error: any, requestConfig: any) => {
console.error("[配置中心] GSC API 错误:", error, requestConfig);
// 检查错误信息中是否包含 401 状态码,待优化项:插件默认所有>=400状态码全部阻塞,后续业务状态码不会捕获处理
const errorMessage = error?.msg || error?.message || error?.toString() || String(error);
if (errorMessage.includes("401")) {
ElMessage.error("登录已过期,请重新登录");
clearAuth();
// 跳转到登录页
if (window.location.pathname !== "/login") {
window.location.href = "/login";
}
} else {
ElMessage.error(errorMessage);
}
},
logout: (response: any, requestConfig: any) => {
console.log("[配置中心] GSC API 登出:", response, requestConfig);
},
},
});
gscApiInstance = new Request(globalDefaults);
// 配置请求拦截器,动态添加 Authorization
gscApiInstance.interceptors.request.use(
(config: any) => {
// 动态获取 token 并添加到请求头
const token = getToken();
if (token) {
config.headers = {
...config.headers,
"Authorization": token
};
}
return config;
},
(error: any) => {
console.error("[配置中心] 请求拦截器错误:", error);
return Promise.reject(error);
}
);
if (configReadyResolve) {
configReadyResolve();
configReadyResolve = null;
}
} else {
console.warn("[配置中心] 未找到 GSC 配置,无法初始化 API 实例");
// 即使没有 GSC 配置,也要 resolve Promise,避免 waitForConfigReady 一直等待
if (configReadyResolve) {
configReadyResolve();
configReadyResolve = null;
}
}
return configData;
} catch (error) {
console.error("[配置中心] 获取配置失败:", error);
// 配置加载失败时,也要 resolve Promise,避免 waitForConfigReady 一直等待
if (configReadyResolve) {
configReadyResolve();
configReadyResolve = null;
}
throw error;
}
}
/**
* 获取当前配置数据
* @returns 配置数据
*/
export function getConfig(): any {
return baseConfig;
}
/**
* 清空配置缓存
* 在项目退出时调用
*/
export function clearConfigCache(): void {
localCache.remove(CONFIG_CACHE_KEY);
localCache.remove(ROUTER_CONFIG_CACHE_KEY);
console.log("[配置中心] 配置缓存已清空");
}
// 导出配置数据(只读)
export { baseConfig };