djConfig.ts
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/** 嘀加旧系统配置中心。地址可由 VITE_DJ_CONFIG_CENTER_URL 覆盖。 */
const env = import.meta.env as Record<string, string | boolean | undefined>;
export const DEFAULT_DJ_CONFIG_CENTER_URL =
'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=dj-car-life-system-config';
function text(name: string, fallback = ''): string {
const value = env[name];
return typeof value === 'string' && value.trim() ? value.trim() : fallback;
}
export interface DjLoginConfig {
baseURL: string;
appKey: string;
secret: string;
account: string;
password: string;
}
interface ConfigCenterAxios {
baseURL?: unknown;
appkey?: unknown;
appKey?: unknown;
secret?: unknown;
}
interface ConfigCenterPayload {
code?: unknown;
data?: unknown;
axios?: ConfigCenterAxios;
}
type ConfigFetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
function parseConfigPayload(response: ConfigCenterPayload): ConfigCenterAxios {
let payload: unknown = response;
// 配置中心实测成功码为 0,旧 Vue 代码还兼容过 200;两种包装都读取 data。
if (response.data) {
if (typeof response.data === 'string') {
try {
payload = JSON.parse(response.data);
} catch {
throw new Error('嘀加配置中心返回的配置内容无法识别');
}
} else {
payload = response.data;
}
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
throw new Error('嘀加配置中心未返回有效配置');
}
const axios = (payload as ConfigCenterPayload).axios;
if (!axios || typeof axios.baseURL !== 'string' || !axios.baseURL.trim()) {
throw new Error('嘀加配置中心缺少接口地址');
}
const appKey = axios.appkey ?? axios.appKey;
if (
typeof appKey !== 'string' ||
!appKey.trim() ||
typeof axios.secret !== 'string' ||
!axios.secret.trim()
) {
throw new Error('嘀加配置中心缺少应用标识或签名配置');
}
return axios;
}
/** 从配置中心读取当前环境的嘀加接口与签名配置,不将返回值写入本地。 */
export async function loadDjLoginConfig(fetcher: ConfigFetcher = fetch): Promise<DjLoginConfig> {
const response = await fetcher(text('VITE_DJ_CONFIG_CENTER_URL', DEFAULT_DJ_CONFIG_CENTER_URL));
if (!response.ok) throw new Error(`嘀加配置中心请求失败(${response.status})`);
const axios = parseConfigPayload((await response.json()) as ConfigCenterPayload);
return {
baseURL: String(axios.baseURL).trim(),
appKey: String(axios.appkey ?? axios.appKey).trim(),
secret: String(axios.secret).trim(),
account: text('VITE_DJ_LOGIN_ACCOUNT', 'glsadmin'),
password: text('VITE_DJ_LOGIN_PASSWORD', '123456'),
};
}