center.ts 6.77 KB
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 };