88 lines
2.2 KiB
JavaScript
88 lines
2.2 KiB
JavaScript
|
|
const env = __VITE_ENV__;
|
||
|
|
|
||
|
|
export const API_CONTEXT_CACHE_KEY = "ykt_team_api_context";
|
||
|
|
|
||
|
|
export const CORP_API_BASE_URL_MAP = {
|
||
|
|
wwa54dfba0b5441ef1: "https://crm.gykqyy.com/ykt/",
|
||
|
|
};
|
||
|
|
|
||
|
|
function normalizeBaseUrl(url) {
|
||
|
|
return String(url || "").replace(/\/+$/, "");
|
||
|
|
}
|
||
|
|
|
||
|
|
function getDefaultBaseUrl() {
|
||
|
|
return normalizeBaseUrl(env.MP_API_BASE_URL);
|
||
|
|
}
|
||
|
|
|
||
|
|
function readCachedContext() {
|
||
|
|
if (typeof uni === "undefined" || typeof uni.getStorageSync !== "function") {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
const cached = uni.getStorageSync(API_CONTEXT_CACHE_KEY);
|
||
|
|
if (!cached || typeof cached !== "object" || !cached.baseUrl) return null;
|
||
|
|
return {
|
||
|
|
corpId: cached.corpId || "",
|
||
|
|
baseUrl: normalizeBaseUrl(cached.baseUrl),
|
||
|
|
};
|
||
|
|
} catch (error) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function writeCachedContext(context) {
|
||
|
|
if (typeof uni === "undefined" || typeof uni.setStorageSync !== "function") {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
try {
|
||
|
|
uni.setStorageSync(API_CONTEXT_CACHE_KEY, {
|
||
|
|
corpId: context.corpId || "",
|
||
|
|
baseUrl: normalizeBaseUrl(context.baseUrl),
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
// 缓存失败不能阻断接口请求。
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function createContext(corpId, baseUrl) {
|
||
|
|
return {
|
||
|
|
corpId: corpId || "",
|
||
|
|
baseUrl: normalizeBaseUrl(baseUrl),
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export function resolveApiContext(corpId) {
|
||
|
|
const normalizedCorpId = String(corpId || "").trim();
|
||
|
|
|
||
|
|
if (normalizedCorpId) {
|
||
|
|
const configuredBaseUrl = CORP_API_BASE_URL_MAP[normalizedCorpId];
|
||
|
|
const context = createContext(
|
||
|
|
normalizedCorpId,
|
||
|
|
configuredBaseUrl || getDefaultBaseUrl()
|
||
|
|
);
|
||
|
|
writeCachedContext(context);
|
||
|
|
return context;
|
||
|
|
}
|
||
|
|
|
||
|
|
const cachedContext = readCachedContext();
|
||
|
|
if (cachedContext) return cachedContext;
|
||
|
|
|
||
|
|
const context = createContext("", getDefaultBaseUrl());
|
||
|
|
writeCachedContext(context);
|
||
|
|
return context;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function getApiBaseUrlByCorpId(corpId) {
|
||
|
|
return resolveApiContext(corpId).baseUrl;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function getDefaultUploadUrl() {
|
||
|
|
return `${getDefaultBaseUrl()}/upload`;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function buildApiUrl(path, corpId) {
|
||
|
|
const { baseUrl } = resolveApiContext(corpId);
|
||
|
|
const normalizedPath = String(path || "").replace(/^\/+/, "");
|
||
|
|
return normalizedPath ? `${baseUrl}/${normalizedPath}` : baseUrl;
|
||
|
|
}
|