gscrequest.ts 2.03 KB
/**
 * GSC 请求封装
 * Authorization 通过请求拦截器统一处理,无需手动添加
 */
import { getGscApi, waitForConfigReady } from "./center";

/**
 * GSC POST 请求
 * @param url 请求地址
 * @param data 请求数据
 * @param config 请求配置(可选)
 */
export const gscPost = async (url: string, data: any, config: any = {}) => {
	// 如果 GSC API 实例未初始化,等待配置加载完成
	const gscApi = getGscApi();
	if (!gscApi) {
		try {
			// 等待配置加载完成
			await waitForConfigReady();
			// 再次尝试获取 GSC API 实例
			const retryGscApi = getGscApi();
			if (!retryGscApi) {
				const error = new Error(
					"[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成且包含 GSC 配置",
				);
				console.error(error);
				throw error;
			}
			return retryGscApi.post(url, data, config);
		} catch (error) {
			console.error("[GSC请求] 等待配置加载失败:", error);
			throw new Error(
				"[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成",
			);
		}
	}

	return gscApi.post(url, data, config);
};

/**
 * GSC GET 请求
 * @param url 请求地址
 * @param config 请求配置(可选)
 */
export const gscGet = async (url: string, config: any = {}) => {
	// 如果 GSC API 实例未初始化,等待配置加载完成
	const gscApi = getGscApi();
	if (!gscApi) {
		try {
			// 等待配置加载完成
			await waitForConfigReady();
			// 再次尝试获取 GSC API 实例
			const retryGscApi = getGscApi();
			if (!retryGscApi) {
				const error = new Error(
					"[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成且包含 GSC 配置",
				);
				console.error(error);
				throw error;
			}
			return retryGscApi.get(url, config);
		} catch (error) {
			console.error("[GSC请求] 等待配置加载失败:", error);
			throw new Error(
				"[GSC请求] GSC API 实例未初始化,请确保配置中心已加载完成",
			);
		}
	}

	return gscApi.get(url, config);
};

// 默认导出
export default gscPost;