apiEnvironments.ts 2.87 KB
/**
 * @file API 环境预设表与小程序 AppId 映射。
 *
 * 运行时由 {@link resolveApiEnvKey} 选用预设 key,再经 {@link resolveApiConfig} 注入 axios。
 *
 * @see {@link activeDevApiEnv} 微信开发者工具联调开关(仅 devtools 生效)
 */

/**
 * API 环境标识。
 *
 * - `test` — 测试服 `aus.test.glsx.com.cn`
 * - `prod` — 生产服 `aus.glsx.com.cn`
 * - `local-125` — 内网 `192.168.1.125:6901`
 * - `local-6901` — 本机 `localhost:6901`
 * - `local-108` — 内网 `192.168.0.108:5001/rest`
 */
export type ApiEnvKey = 'test' | 'prod' | 'local-125' | 'local-6901' | 'local-108';

/**
 * 单个 API 环境的 URL 配置。
 */
export interface ApiEnvConfig {
    /** Axios `baseURL` */
    apiUrl: string;
    /** 业务根路径(静态资源等) */
    baseUrl: string;
    /** 人类可读名称,用于日志或 UI 展示 */
    label: string;
    /** 微信小程序 AppId,与后端 `wx.miniapp` 配置对应 */
    miniProgramAppId: string;
}

/**
 * 运行时 API 预设表。
 */
export const API_ENVIRONMENTS: Record<ApiEnvKey, ApiEnvConfig> = {
    test: {
        label: '测试 aus.test',
        apiUrl: 'https://aus.test.glsx.com.cn/app/api/',
        baseUrl: 'https://aus.test.glsx.com.cn/app/',
        miniProgramAppId: 'wx568d02f6352efd49',
    },
    prod: {
        label: '生产 aus',
        apiUrl: 'https://aus.glsx.com.cn/app/api/',
        baseUrl: 'https://aus.glsx.com.cn/app/',
        miniProgramAppId: 'wxa719209ed933d667',
    },
    'local-125': {
        label: '内网 192.168.1.125',
        apiUrl: 'http://192.168.1.125:6901/api/',
        baseUrl: 'http://192.168.1.125:6901/',
        miniProgramAppId: 'wx568d02f6352efd49',
    },
    'local-6901': {
        label: '本机 localhost:6901',
        apiUrl: 'http://localhost:6901/api/',
        baseUrl: 'http://localhost:6901/',
        miniProgramAppId: 'wx568d02f6352efd49',
    },
    'local-108': {
        label: '内网 192.168.0.108',
        apiUrl: 'http://192.168.0.108:5001/rest/api/',
        baseUrl: 'http://192.168.0.108:5001/rest/',
        miniProgramAppId: 'wx568d02f6352efd49',
    },
};

/** 小程序 AppId → API 环境 key(体验版 / 开发版运行时映射) */
export const APP_ID_TO_ENV: Record<string, ApiEnvKey> = {
    'wx568d02f6352efd49': 'test',
    'wxa719209ed933d667': 'prod',
};

/** `API_ENVIRONMENTS` 的全部 key */
export const API_ENV_KEYS = Object.keys(API_ENVIRONMENTS) as ApiEnvKey[];

/**
 * 判断字符串是否为合法的 {@link ApiEnvKey}。
 */
export function isApiEnvKey(key: string): key is ApiEnvKey {
    return (API_ENV_KEYS as string[]).includes(key);
}

/**
 * 根据小程序 AppId 解析 API 环境 key。
 */
export function resolveEnvKeyFromAppId(appId: string): ApiEnvKey | undefined {
    const normalized = appId?.trim();
    if (!normalized) {
        return undefined;
    }
    return APP_ID_TO_ENV[normalized];
}