index.ts
7.32 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
/**
* 兼容旧版 Vue 项目的 ROP 接口客户端。
*
* 它与 ../core 的 REST + RSA 客户端完全独立:不复用其签名、登录凭证或拦截器。
* ROP 服务通常只有一个路由入口,通过请求参数中的 method 区分业务接口。
*/
import axios, { type AxiosAdapter, type AxiosRequestConfig, type Method } from 'axios';
import { KJUR } from 'jsrsasign';
export type RopSignWay = 'sha1' | 'md5';
export type RopRequestMethod = 'get' | 'post' | 'put' | 'delete';
export type RopPayload = Record<string, unknown>;
export interface RopResultRule {
/** 返回状态字段,默认 code */
codeKey?: string;
/** 成功状态值,默认 0 */
successCode?: string | number;
/** 业务数据字段,默认 data */
dataKey?: string;
/** 错误说明字段,默认 message */
messageKey?: string;
}
export interface RopClientConfig {
/** ROP 路由入口地址,例如 https://example.com/router */
baseURL: string;
appKey: string;
/** ROP 共享密钥;请通过环境配置提供,不要写入业务页面。 */
secret: string;
signWay?: RopSignWay;
timeout?: number;
/** 非登录请求自动附带的会话标识。 */
getSessionId?: () => string | null | undefined;
/** 默认 dj.api.user.login;该接口不附带 sessionId。 */
loginMethod?: string;
result?: RopResultRule;
/** 测试或特殊网络场景可替换发送适配器。 */
adapter?: AxiosAdapter;
/** 仅用于测试;生产环境默认取当前时间。 */
now?: () => number;
}
export interface RopRequestOptions {
/** 返回服务端完整内容;默认只返回 data。 */
returnAll?: boolean;
signal?: AbortSignal;
headers?: Record<string, string>;
onUploadProgress?: AxiosRequestConfig['onUploadProgress'];
}
interface RequiredRopResultRule {
codeKey: string;
successCode: string | number;
dataKey: string;
messageKey: string;
}
const DEFAULT_RESULT_RULE: RequiredRopResultRule = {
codeKey: 'code',
successCode: 0,
dataKey: 'data',
messageKey: 'message',
};
function isPlainObject(value: unknown): value is Record<string, unknown> {
return Object.prototype.toString.call(value) === '[object Object]';
}
/**
* 按旧 Vue 项目 qs.stringify({ arrayFormat: 'indices', allowDots: true }) 的字段命名展开对象。
* undefined 会被旧实现的 JSON 深拷贝忽略;null 会作为空字符串参与签名。
*/
function flattenPayload(
value: unknown,
prefix = '',
output: Record<string, string> = {},
): Record<string, string> {
if (value === undefined) return output;
if (value === null) {
output[prefix] = '';
return output;
}
if (Array.isArray(value)) {
value.forEach((item, index) => flattenPayload(item, `${prefix}[${index}]`, output));
return output;
}
if (isPlainObject(value)) {
Object.keys(value).forEach((key) => {
flattenPayload(value[key], prefix ? `${prefix}.${key}` : key, output);
});
return output;
}
output[prefix] = String(value);
return output;
}
function normalizePayload(payload: RopPayload): Record<string, string> {
// 旧版实现先 JSON 深拷贝;这里保留相同的 undefined 忽略行为,且不修改调用方对象。
return flattenPayload(payload);
}
/** 按 ROP 旧规则生成签名后的平铺参数。 */
export function signRopPayload(
payload: RopPayload,
config: Pick<RopClientConfig, 'secret' | 'signWay'>,
noSignAttrs: readonly string[] = [],
): Record<string, string> {
const params = normalizePayload(payload);
delete params.sign;
const sortedKeys = Object.keys(params).sort();
const canonical = sortedKeys
.filter((key) => !noSignAttrs.includes(key))
.map((key) => key + params[key])
.join('');
const signWay = config.signWay ?? 'sha1';
params.sign = KJUR.crypto.Util.hashString(
config.secret + canonical + config.secret,
signWay,
).toUpperCase();
return params;
}
function toFormBody(params: Record<string, string>): string {
return new URLSearchParams(params).toString();
}
function resolveResponse<T>(body: unknown, rule: RequiredRopResultRule, returnAll: boolean): T {
if (returnAll) return body as T;
if (!isPlainObject(body)) throw new Error('ROP 接口返回内容格式不正确');
const code = body[rule.codeKey] ?? body.returnCode;
const message = body[rule.messageKey];
if (String(code) !== String(rule.successCode)) {
const error = new Error(
typeof message === 'string' && message ? message : 'ROP 接口请求失败',
) as Error & { code?: unknown; data?: unknown };
error.code = code;
error.data = body[rule.dataKey];
throw error;
}
return body[rule.dataKey] as T;
}
export interface RopClient {
request<T>(
method: RopRequestMethod,
payload: RopPayload,
options?: RopRequestOptions,
noSignAttrs?: readonly string[],
): Promise<T>;
get<T>(
payload: RopPayload,
options?: RopRequestOptions,
noSignAttrs?: readonly string[],
): Promise<T>;
post<T>(
payload: RopPayload,
options?: RopRequestOptions,
noSignAttrs?: readonly string[],
): Promise<T>;
put<T>(
payload: RopPayload,
options?: RopRequestOptions,
noSignAttrs?: readonly string[],
): Promise<T>;
del<T>(
payload: RopPayload,
options?: RopRequestOptions,
noSignAttrs?: readonly string[],
): Promise<T>;
}
/**
* 创建独立的 ROP 客户端。每个旧系统可传入自己的地址、appKey 与密钥,互不影响。
*/
export function createRopClient(config: RopClientConfig): RopClient {
const http = axios.create({
baseURL: config.baseURL,
timeout: config.timeout ?? 100000,
adapter: config.adapter,
});
const resultRule: RequiredRopResultRule = { ...DEFAULT_RESULT_RULE, ...config.result };
const loginMethod = config.loginMethod ?? 'dj.api.user.login';
const now = config.now ?? Date.now;
async function request<T>(
method: RopRequestMethod,
payload: RopPayload,
options: RopRequestOptions = {},
noSignAttrs: readonly string[] = [],
): Promise<T> {
const common: RopPayload = {
...payload,
appKey: config.appKey,
timestamp: now(),
v: '1.0.0',
format: 'json',
locale: 'zh_CN',
};
if (payload.method !== loginMethod) {
const sessionId = config.getSessionId?.();
if (sessionId) common.sessionId = sessionId;
}
const signed = signRopPayload(common, config, noSignAttrs);
const requestConfig: AxiosRequestConfig = {
method: method as Method,
signal: options.signal,
headers: options.headers,
onUploadProgress: options.onUploadProgress,
};
if (method === 'get' || method === 'delete') {
requestConfig.params = signed;
} else {
requestConfig.data = toFormBody(signed);
requestConfig.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
...options.headers,
};
}
const response = await http.request(requestConfig);
return resolveResponse<T>(response.data, resultRule, options.returnAll === true);
}
return {
request,
get: (payload, options, noSignAttrs) => request('get', payload, options, noSignAttrs),
post: (payload, options, noSignAttrs) => request('post', payload, options, noSignAttrs),
put: (payload, options, noSignAttrs) => request('put', payload, options, noSignAttrs),
del: (payload, options, noSignAttrs) => request('delete', payload, options, noSignAttrs),
};
}