2026-06-17 03:36:58 +08:00

36 lines
1.1 KiB
JavaScript

export function normalizeFrontendAPIBaseURL(value = "") {
const raw = String(value || "").trim();
if (!raw) {
return "";
}
const normalized = raw.replace(/\/+$/, "");
let parsed;
try {
parsed = new URL(normalized);
} catch {
throw new Error(`VITE_API_BASE_URL must be empty or an absolute http(s) URL: ${raw}`);
}
if (!["http:", "https:"].includes(parsed.protocol) || !parsed.host) {
throw new Error(`VITE_API_BASE_URL must be empty or an absolute http(s) URL: ${raw}`);
}
return normalized;
}
export function createAPIURLBuilder(baseURL = "") {
const normalizedBaseURL = normalizeFrontendAPIBaseURL(baseURL);
return (path) => {
const normalizedPath = String(path || "");
if (!normalizedPath.startsWith("/")) {
throw new Error(`API request path must start with "/": ${normalizedPath}`);
}
return `${normalizedBaseURL}${normalizedPath}`;
};
}
export function viteAPIBaseURL(meta = import.meta) {
return normalizeFrontendAPIBaseURL(meta?.env?.VITE_API_BASE_URL || "");
}
export const API_BASE_URL = viteAPIBaseURL();
export const buildAPIURL = createAPIURLBuilder(API_BASE_URL);