gscRequest.ts 3.24 KB
import type { Request } from "glsk-toolkit";
import type { QiankunProps } from "vite-plugin-qiankun/dist/helper";

import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";

/**
 * GSC Request 管理器
 * 用于管理从基座获取的 Request 实例
 */
class GscRequestManager {
	private getGscRequestFn: (() => Promise<Request>) | null = null;
	private initPromise: null | Promise<Request> = null;
	private requestInstance: null | Request = null;

	/**
   * 销毁管理器
   */
	destroy() {
		this.requestInstance = null;
		this.getGscRequestFn = null;
		this.initPromise = null;
	}

	/**
   * 获取 GSC Request 实例
   * @returns Promise<Request> Request 实例
   */
	async getRequest(): Promise<Request> {
		// 如果已有实例,直接返回
		if (this.requestInstance) {
			return this.requestInstance;
		}

		// 如果有获取函数,尝试获取
		if (this.getGscRequestFn) {
			// 如果正在初始化,等待初始化完成
			if (this.initPromise) {
				return this.initPromise;
			}

			// 创建初始化 Promise
			this.initPromise = this.getGscRequestFn().then((instance) => {
				this.requestInstance = instance;
				this.initPromise = null;
				return instance;
			});

			return this.initPromise;
		}

		throw new Error(
			"[GSC Request] Request 未初始化,请确保在 qiankun 环境中运行并已调用 init 方法",
		);
	}

	/**
   * 初始化 GSC Request(在子应用 render 函数中调用)
   * @param props qiankun 传递的 props
   */
	async init(props: QiankunProps) {
		if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
			console.warn("[GSC Request] 非 qiankun 环境,无法获取 Request 实例");
			return;
		}

		if (!props.getGscRequest) {
			console.warn("[GSC Request] props 中未找到 getGscRequest 函数");
			return;
		}

		this.getGscRequestFn = props.getGscRequest;

		try {
			if (this.getGscRequestFn) {
				this.requestInstance = await this.getGscRequestFn();
			}
		} catch (error) {
			console.error("[GSC Request] 实例初始化失败:", error);
			throw error;
		}
	}

	/**
   * 检查 Request 是否已初始化
   */
	isInitialized(): boolean {
		return this.requestInstance !== null;
	}
}

// 导出单例
export const gscRequestManager = new GscRequestManager();

/**
 * GSC POST 请求封装(类似基座的 gscPost)
 * @param url 请求地址
 * @param data 请求数据
 * @param config 请求配置
 * @returns Promise<any> 响应数据
 */
export async function gscPost(
	url: string,
	data: any,
	config: any = {},
): Promise<any> {
	const request = await gscRequestManager.getRequest();
	// Request 实例有 post 方法,但类型定义可能不完整,使用类型断言
	return (request as any).post(url, data, config);
}

/**
 * GSC GET 请求封装
 * @param url 请求地址
 * @param config 请求配置
 * @returns Promise<any> 响应数据
 */
export async function gscGet(url: string, config: any = {}): Promise<any> {
	const request = await gscRequestManager.getRequest();
	// Request 实例有 get 方法,但类型定义可能不完整,使用类型断言
	return (request as any).get(url, config);
}

/**
 * 直接获取 Request 实例(高级用法)
 * @returns Promise<Request> Request 实例
 */
export async function getGscRequest(): Promise<Request> {
	return gscRequestManager.getRequest();
}