loadAxiosConfig.js 3.01 KB
const fs = require("fs");
const http = require("http");
const https = require("https");
const path = require("path");
const { getAxiosConfigKey } = require("./resolveApiName");

function tryParseJson(raw) {
	if (typeof raw !== "string" || !raw.trim()) {
		return null;
	}
	try {
		return JSON.parse(raw);
	} catch (error) {
		return null;
	}
}

function parseConfigCenterResponse(response) {
	if (!response || typeof response !== "object") {
		return null;
	}
	let payload = response;
	if (response.code == "200" && response.data) {
		payload = typeof response.data === "string"
			? tryParseJson(response.data)
			: response.data;
	}
	if (
		payload
		&& typeof payload === "object"
		&& payload.axios?.baseURL
		&& payload.axios?.appkey
	) {
		return payload;
	}
	return null;
}

const DEFAULT_CONFIG_URL = process.env.VUE_APP_CONFIG_CENTER_URL
	|| "https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=dj-car-life-system-config";

const DEVELOP_CONFIG_PATH = path.join(__dirname, "../../common/baseConfig.develop.json");

function fetchJson(url) {
	return new Promise((resolve, reject) => {
		const lib = url.startsWith("https") ? https : http;
		lib.get(url, (res) => {
			let raw = "";
			res.on("data", (chunk) => { raw += chunk; });
			res.on("end", () => {
				try {
					resolve(JSON.parse(raw));
				} catch (error) {
					reject(new Error(`JSON parse failed: ${raw.slice(0, 200)}`));
				}
			});
		}).on("error", reject);
	});
}

function loadDevelopFallback() {
	return JSON.parse(fs.readFileSync(DEVELOP_CONFIG_PATH, "utf8"));
}

function pickAxiosBlock(baseConfig, apiName = "dj") {
	const configKey = getAxiosConfigKey(apiName);
	if (!configKey) {
		throw new Error(`Unknown apiName for axios config: ${apiName}`);
	}
	const block = baseConfig?.[configKey];
	if (!block?.baseURL || !block?.appkey || !block?.secret) {
		throw new Error(`Invalid ROP config: missing ${configKey}.baseURL/appkey/secret`);
	}
	return {
		baseURL: block.baseURL,
		appkey: block.appkey,
		secret: block.secret,
		configKey,
	};
}

/**
 * 加载 axios 配置:优先配置中心,失败回退 baseConfig.develop.json
 * @param {string|{ configUrl?: string, apiName?: string }} options
 */
async function loadAxiosConfig(options) {
	let configUrl = DEFAULT_CONFIG_URL;
	let apiName = "dj";
	if (typeof options === "string") {
		configUrl = options;
	} else if (options && typeof options === "object") {
		configUrl = options.configUrl || DEFAULT_CONFIG_URL;
		apiName = options.apiName || "dj";
	}

	let baseConfig = null;
	try {
		const response = await fetchJson(configUrl);
		baseConfig = parseConfigCenterResponse(response);
	} catch (error) {
		// 回退 develop 本地配置
	}
	if (!baseConfig?.axios?.appkey || !baseConfig?.axios?.secret) {
		baseConfig = loadDevelopFallback();
	}

	const { baseURL, appkey, secret, configKey } = pickAxiosBlock(baseConfig, apiName);
	return {
		baseURL,
		appkey,
		secret,
		env: baseConfig.env,
		apiName,
		configKey,
	};
}

module.exports = {
	loadAxiosConfig,
	loadDevelopFallback,
	pickAxiosBlock,
	DEFAULT_CONFIG_URL,
};