ropRequest.ts
8.5 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { getConfig } from "@/config/center";
import { TOKEN_KEY } from "@/config/constants";
import axios, { AxiosInstance, AxiosResponse } from "axios";
import { showToast } from "vant";
import { stringify as qsStringify } from "./qs";
import sha1 from "./sha1";
export interface RequestConfig {
[key: string]: unknown;
headers?: Record<string, string>;
params?: Record<string, unknown>;
}
type ApiResponse<T = unknown> = {
code?: number | string;
data?: T;
message?: string;
msg?: string;
success?: boolean;
};
const BIZ_CODES_OK = new Set([0, 200]);
const BIZ_CODE_UNAUTHORIZED = 1006;
function normalizeBizCode(code: unknown): null | number {
if (code === null || code === undefined || code === "") return null;
const n = Number(code);
return Number.isNaN(n) ? null : n;
}
function redirectToLogin(message?: string) {
showToast(message || "登录已过期,请重新登录");
localStorage.removeItem(TOKEN_KEY);
window.location.href = "/login";
}
function getSecretKey(service?: string): string {
const cfg = getConfig() as Record<string, unknown>;
let env: undefined | { secret?: string };
switch (service) {
case "boutique": {
env = cfg.boutiqueApiEnv as undefined | { secret?: string };
break;
}
case "sso": {
env = cfg.ssoApiEnv as undefined | { secret?: string };
break;
}
case "sto":
case "stoassistant": {
env = cfg.stoApiEnv as undefined | { secret?: string };
break;
}
default: {
env = cfg.clueApiEnv as undefined | { secret?: string };
break;
}
}
return env?.secret ?? "";
}
function getAppKey(service?: string): string {
const cfg = getConfig() as Record<string, unknown>;
let env: undefined | { appKey?: string };
switch (service) {
case "boutique": {
env = cfg.boutiqueApiEnv as undefined | { appKey?: string };
break;
}
case "sso": {
env = cfg.ssoApiEnv as undefined | { appKey?: string };
break;
}
case "sto":
case "stoassistant": {
env = cfg.stoApiEnv as undefined | { appKey?: string };
break;
}
default: {
env = cfg.clueApiEnv as undefined | { appKey?: string };
break;
}
}
return env?.appKey ?? "";
}
function signParams(params: Record<string, unknown>, secret: string, noSignAttr: string[] = []): Record<string, string> {
delete (params as { sign?: unknown }).sign;
const objStr = qsStringify(params, {
arrayFormat: "indices",
allowDots: true,
encodeValuesOnly: true,
});
const objVal = objStr.split("&").filter(Boolean);
const realObj: Record<string, string> = {};
for (const item of objVal) {
const idx = item.indexOf("=");
const key = idx === -1 ? item : item.slice(0, idx);
const val = idx === -1 ? "" : item.slice(idx + 1);
realObj[key] = decodeURIComponent(val);
}
const keys = Object.keys(realObj).sort();
const parts: string[] = [];
for (const key of keys) {
if (!noSignAttr.includes(key)) parts.push(key + realObj[key]);
}
realObj.sign = sha1(`${secret}${parts.join("")}${secret}`).toUpperCase();
return realObj;
}
function buildParams(method: string, raw?: unknown, service?: string): Record<string, string> {
const data = (raw && typeof raw === "object" ? { ...(raw as Record<string, unknown>) } : {}) as Record<string, unknown>;
data.v = "1.0.0";
data.method = method;
data.format = "json";
data.locale = "zh_CN";
data.source = "app";
const secretKey = getSecretKey(service);
data.appKey = getAppKey(service);
return signParams(data, secretKey);
}
function applyAuthInterceptor(instance: AxiosInstance) {
instance.interceptors.request.use(
(config) => {
return config;
},
(error) => Promise.reject(error)
);
}
function applyHttpErrorInterceptor(instance: AxiosInstance) {
instance.interceptors.response.use(
(response) => response,
(error) => {
const status = error?.response?.status as number | undefined;
const msg = error?.response?.data?.message || error?.message || "网络错误,请检查网络连接";
switch (status) {
case 401: {
redirectToLogin();
break;
}
case 403: {
showToast("暂无权限");
break;
}
case 500: {
showToast("服务器异常,请稍后重试");
break;
}
default: {
showToast(msg);
}
}
return Promise.reject(error);
}
);
}
async function handleResponse<T>(promise: Promise<AxiosResponse<ApiResponse<T> | T>>): Promise<T> {
const res = await promise;
const raw = res.data as ApiResponse<T> | T;
if (typeof raw === "object" && raw && ("code" in raw || "success" in raw)) {
const biz = raw as ApiResponse<T>;
const codeNum = normalizeBizCode(biz.code);
const isSuccess = (codeNum !== null && BIZ_CODES_OK.has(codeNum)) || (codeNum === null && biz.success === true);
if (isSuccess) {
return (biz.data ?? (raw as unknown)) as T;
}
const errMsg = biz.message || biz.msg || "请求失败";
if (codeNum === BIZ_CODE_UNAUTHORIZED) {
redirectToLogin(errMsg);
throw new Error(errMsg);
}
showToast(errMsg);
throw new Error(errMsg);
}
return raw as T;
}
type RopService = {
resolveBaseURL: () => string;
};
type ServiceName = "boutique" | "clue" | "sso" | "stoassistant" | (string & {});
const DEFAULT_SERVICES: Record<"boutique" | "clue" | "sso" | "stoassistant", RopService> = {
stoassistant: {
resolveBaseURL: () => {
const cfg = getConfig() as Record<string, unknown>;
const apiBaseUrl =
((cfg.stoApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseURL ??
(cfg.stoApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseUrl ??
"") as string | undefined;
return apiBaseUrl || "/";
},
},
sso: {
resolveBaseURL: () => {
const cfg = getConfig() as Record<string, unknown>;
const apiBaseUrl =
((cfg.ssoApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseURL ??
(cfg.ssoApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseUrl ??
"") as string | undefined;
return apiBaseUrl || "/";
},
},
boutique: {
resolveBaseURL: () => {
const cfg = getConfig() as Record<string, unknown>;
const apiBaseUrl =
((cfg.boutiqueApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseURL ??
(cfg.boutiqueApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseUrl ??
"") as string | undefined;
return apiBaseUrl || "/";
},
},
clue: {
resolveBaseURL: () => {
const cfg = getConfig() as Record<string, unknown>;
const apiBaseUrl =
((cfg.clueApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseURL ??
(cfg.clueApiEnv as undefined | { baseURL?: string; baseUrl?: string })?.baseUrl ??
"") as string | undefined;
return apiBaseUrl || "/";
},
},
};
const serviceRegistry = new Map<ServiceName, RopService>(Object.entries(DEFAULT_SERVICES) as any);
const instanceRegistry = new Map<ServiceName, AxiosInstance>();
export function registerRopService(name: ServiceName, service: RopService) {
serviceRegistry.set(name, service);
instanceRegistry.delete(name);
}
function encodeFormUrl(data: unknown) {
if (data instanceof URLSearchParams) return data.toString();
if (!data || typeof data !== "object") return data;
return Object.keys(data as Record<string, unknown>)
.map((key) => {
const val = (data as Record<string, unknown>)[key];
if (val === null || val === undefined || typeof val === "object") return "";
return `${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`;
})
.filter((str) => str !== "")
.join("&");
}
function getRopInstance(service: ServiceName): AxiosInstance {
const cached = instanceRegistry.get(service);
if (cached) return cached;
const entry = serviceRegistry.get(service);
if (!entry) {
throw new Error(`Unknown rop service: ${service}`);
}
const baseURL = entry.resolveBaseURL();
const instance = axios.create({
timeout: 15_000,
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
transformRequest: [encodeFormUrl],
});
applyAuthInterceptor(instance);
instance.interceptors.request.use(
(config) => {
config.url = `${baseURL}?method=${config.url}`;
return config;
},
(error) => Promise.reject(error)
);
applyHttpErrorInterceptor(instance);
instanceRegistry.set(service, instance);
return instance;
}
export function ropPost<T = unknown>(service: ServiceName, method: string, data?: unknown, config?: RequestConfig) {
const instance = getRopInstance(service);
const payload = buildParams(method, data, service);
return handleResponse<T>(instance.post(method, payload, config));
}
export function ssoPost<T = unknown>(method: string, data?: unknown, config?: RequestConfig) {
return ropPost<T>("sso", method, data, config);
}