Files
persionalBrand/apps/api/src/modules/admin/miniapp-build-config.ts
T
que01 d0a0eeea8c
CI / Browser smoke (pull_request) Successful in 58s
CI / Static checks (pull_request) Successful in 1m32s
CI / API integration (pull_request) Successful in 1m27s
CI / Production build (pull_request) Successful in 2m7s
feat: 支持按品牌配置微信登录凭据
2026-10-23 22:07:39 +08:00

59 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
function normalizeBaseUrl(value: string): string {
return value.trim().replace(/\/+$/, "");
}
/**
* 请求地址优先取品牌在后台维护的值,其次才是环境变量。
* 小程序包内的 `API_BASE_URL` 是编译期常量,改地址需要重新构建上传,
* 但地址本身属于可在后台修改的配置,不再写死在服务端环境变量里。
*/
export function miniappApiBaseUrl(
storedApiBaseUrl?: unknown,
env: NodeJS.ProcessEnv = process.env,
): string {
const stored =
typeof storedApiBaseUrl === "string" && storedApiBaseUrl.trim()
? storedApiBaseUrl.trim()
: undefined;
if (stored) return validate(normalizeBaseUrl(stored));
const explicit = env.MINIAPP_API_BASE_URL?.trim();
if (explicit) return validate(normalizeBaseUrl(explicit));
const publicBase = env.PUBLIC_BASE_URL?.trim();
if (publicBase)
return validate(
normalizeBaseUrl(`${normalizeBaseUrl(publicBase)}${env.MINIAPP_API_PATH ?? "/api"}`),
);
throw new Error(
"未配置小程序请求地址:请在“配置与发布 → 小程序配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
);
}
/** 保存前校验后台填写的请求地址,错误信息直接给到管理员。 */
export function validateApiBaseUrl(value: string): string {
return validate(normalizeBaseUrl(value));
}
function validate(value: string): string {
let url: URL;
try {
url = new URL(value);
} catch {
throw new Error(`小程序请求地址不是合法 URL:${value}`);
}
if (url.protocol !== "https:" && !LOCAL_HOSTS.has(url.hostname))
throw new Error(`小程序请求地址必须使用 https(当前 ${value}),否则真机无法访问`);
return value;
}
export function weappAppId(storedAppId: unknown, env: NodeJS.ProcessEnv = process.env): string {
const candidate =
typeof storedAppId === "string" && storedAppId.trim()
? storedAppId.trim()
: (env.WEAPP_APP_ID?.trim() ?? "");
if (!candidate || candidate === "undefined" || candidate === "touristappid")
throw new Error("未配置微信 AppID:请在“小程序配置”里填写或设置 WEAPP_APP_ID");
return candidate;
}