@hzab/data-model 2.0.3-alpha.1 → 2.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,202 +0,0 @@
1
- import { InternalAxiosRequestConfig } from "axios";
2
- import { axiosDef } from "./axios";
3
-
4
- /**
5
- * 缓存配置
6
- */
7
- export interface CacheOpt {
8
- /** 缓存时间 毫秒 */
9
- cacheTTL?: number;
10
- }
11
-
12
- /**
13
- * 缓存方法入参配置
14
- */
15
- export interface RequestCacheParams {
16
- options?: CacheOpt;
17
- }
18
-
19
- /**
20
- * 接口入参(用于生成缓存 key)
21
- */
22
- export interface Req {
23
- method?: string;
24
- baseURL?: string;
25
- url?: string;
26
- params?: unknown;
27
- data?: unknown;
28
- }
29
-
30
- /**
31
- * 缓存对象
32
- */
33
- export interface CacheItem {
34
- key: string;
35
- /** 过期时间戳 */
36
- expires?: number;
37
- /** 缓存的 promise */
38
- promise?: Promise<unknown>;
39
- /** 缓存的 axios config 配置 */
40
- config?: InternalAxiosRequestConfig;
41
- resolve: (d) => void;
42
- reject: (err) => void;
43
- }
44
-
45
- /**
46
- * 接口缓存类
47
- */
48
- export class RequestCache {
49
- options: CacheOpt;
50
- cacheTTL = 3000;
51
- /** 存储为 CacheItem(类型为 unknown,返回时断言) */
52
- _cacheMap: Map<string, CacheItem> = new Map();
53
-
54
- constructor(params: RequestCacheParams) {
55
- const { options = {} } = params || {};
56
- this.cacheTTL = options?.cacheTTL ?? 3000;
57
- this.options = options;
58
- }
59
-
60
- /**
61
- * 处理 axios request 拦截逻辑
62
- * @param config
63
- * @returns
64
- */
65
- handleAxRequest(config) {
66
- if (this.hasCache(config)) {
67
- const cache = this.getCache(config);
68
- // 存在缓存,
69
- return Promise.reject({
70
- code: 200,
71
- key: this.getCacheKey(config),
72
- config,
73
- from: "cache",
74
- cache,
75
- });
76
- }
77
- this.rmCache(config);
78
-
79
- const cacheData = {
80
- code: 200,
81
- key: this.getCacheKey(config),
82
- config,
83
- from: "cache",
84
- promise: undefined,
85
- resolve: undefined,
86
- reject: undefined,
87
- };
88
- // 设置 promise 保持请求挂起状态
89
- cacheData.promise = new Promise((resolve, reject) => {
90
- cacheData.resolve = resolve;
91
- cacheData.reject = reject;
92
- });
93
-
94
- config.cache = this.addCache(cacheData);
95
- return config;
96
- }
97
-
98
- /**
99
- * 判断是否存在缓存
100
- * @param axConf
101
- * @returns
102
- */
103
- hasCache(axConf) {
104
- const key = this.getCacheKey(axConf);
105
- const cache = this._cacheMap.get(key);
106
- if (cache && cache.expires >= Date.now()) {
107
- return true;
108
- }
109
- // 过期清除
110
- this._cacheMap.delete(key);
111
- return false;
112
- }
113
-
114
- /**
115
- * 获取缓存
116
- * @param axios config
117
- * @param opt 自定义缓存配置
118
- * @returns Promise<T>
119
- */
120
- getCache(axConf, opt?: CacheOpt): CacheItem {
121
- const key = this.getCacheKey(axConf);
122
-
123
- return this.getCacheByKey(key, opt);
124
- }
125
-
126
- /**
127
- * 获取缓存
128
- * @param key string
129
- * @param opt 自定义缓存配置
130
- * @returns Promise<T>
131
- */
132
- getCacheByKey(key, opt?: CacheOpt) {
133
- // TODO: 过期处理? 结果和请求分开。只有请求才进行过期判断?
134
- // 存在未过期的缓存
135
- const cached = this._cacheMap.get(key);
136
- if (cached && cached.expires > Date.now()) {
137
- return cached;
138
- }
139
-
140
- // 过期删除
141
- if (cached) {
142
- this._cacheMap.delete(key);
143
- }
144
- }
145
-
146
- /**
147
- * 添加缓存
148
- * @param promise 要缓存的 Promise
149
- * @param req 请求描述对象
150
- * @param config 缓存配置
151
- */
152
- addCache(data: CacheItem, opt: CacheOpt = this.options): CacheItem {
153
- const { config } = data || {};
154
- const key = this.getCacheKey(config);
155
- if (this._cacheMap.has(key)) {
156
- return this._cacheMap.get(key);
157
- }
158
- const ttl = opt?.cacheTTL ?? this.cacheTTL;
159
- const cache = {
160
- ...data,
161
- key,
162
- expires: Date.now() + ttl,
163
- config: config,
164
- promise: data.promise,
165
- };
166
- this._cacheMap.set(key, cache);
167
- return cache;
168
- }
169
-
170
- rmCache(config: Req) {
171
- this._cacheMap.delete(this.getCacheKey(config));
172
- }
173
-
174
- /**
175
- * 获取缓存的 key
176
- * @param config 请求入参
177
- * @returns 缓存键字符串
178
- */
179
- getCacheKey(config: Req): string {
180
- const { baseURL, method, url, params, data } = config;
181
- // 注意:params 和 data 需要序列化,并保证对象属性顺序稳定性
182
- return `${method}:${baseURL}/${url}:${this.stableStringify(params)}:${this.stableStringify(data)}`;
183
- }
184
-
185
- /**
186
- * 序列化对象,保证属性顺序一致
187
- * @param obj 任意值
188
- * @returns JSON 字符串
189
- */
190
- private stableStringify(obj: unknown): string {
191
- if (!obj || typeof obj !== "object") return JSON.stringify(obj);
192
- const sorted = Object.keys(obj)
193
- .sort()
194
- .reduce((acc, key) => {
195
- acc[key] = (obj as Record<string, unknown>)[key];
196
- return acc;
197
- }, {} as Record<string, unknown>);
198
- return JSON.stringify(sorted);
199
- }
200
- }
201
-
202
- export default RequestCache;
@@ -1,479 +0,0 @@
1
- import { merge, pickBy, isNil, cloneDeep } from "lodash-es";
2
-
3
- import ArrayUtils, { STATE_CODE, FindListResult, ArrayUtilsOptions } from "./ArrayUtils";
4
-
5
- import { JSONObject, QueryParams, RequestData, MapFunction, RequestMapFunction, GetListFunc } from "./type";
6
-
7
- const errMsg: Record<number | string, string> = {
8
- 404: "未找到对应子项",
9
- 501: "未传入表单 id",
10
- };
11
-
12
- /**
13
- * ArrayDataModel 构造函数参数接口
14
- */
15
- export interface ArrayDataModelOptions<R = any> extends ArrayUtilsOptions<R> {
16
- /** 请求 url 替换的额外参数 */
17
- ctx?: JSONObject;
18
- /** GET 请求的参数 */
19
- query?: QueryParams;
20
-
21
- /** POST 接口地址 */
22
- createApi?: string;
23
- /** POST 接口提交前的数据处理回调 */
24
- createMap?: MapFunction;
25
- /** GET 详情 接口地址 */
26
- getApi?: string;
27
- /** GET 详情 接口返回后的数据处理回调 */
28
- getMap?: MapFunction;
29
- /** GET 列表 接口地址 */
30
- getListApi?: string;
31
- /** GET 列表 接口返回后的数据处理回调 */
32
- getListMap?: MapFunction;
33
- /** GET 列表 接口回调,用于自定义列表请求接口 */
34
- getListFunc?: GetListFunc<R>;
35
- /** PUT 接口地址 */
36
- updateApi?: string;
37
- /** PUT 接口提交前的数据处理回调 */
38
- updateMap?: MapFunction;
39
- /** PATCH 接口地址 */
40
- patchApi?: string;
41
- /** PATCH 接口提交前的数据处理回调 */
42
- patchMap?: MapFunction;
43
- /** DELETE 接口地址 */
44
- deleteApi?: string;
45
- /** DELETE 批量删除 接口地址 */
46
- multipleDeleteApi?: string;
47
-
48
- /** GET 列表 接口请求前数据处理回调 */
49
- getListReqMap?: RequestMapFunction<QueryParams>;
50
- /** GET 列表 接口请求结果数据处理回调 */
51
- getListResMap?: MapFunction;
52
- /** GET 详情 接口请求前数据处理回调 */
53
- getReqMap?: RequestMapFunction<QueryParams>;
54
- /** GET 详情 接口请求结果数据处理回调 */
55
- getResMap?: MapFunction;
56
- /** POST 接口请求前数据处理回调 */
57
- createReqMap?: RequestMapFunction<RequestData>;
58
- /** POST 接口请求结果数据处理回调 */
59
- createResMap?: MapFunction;
60
- /** PUT 接口请求前数据处理回调 */
61
- updateReqMap?: RequestMapFunction<RequestData>;
62
- /** PUT 接口请求结果数据处理回调 */
63
- updateResMap?: MapFunction;
64
- /** PATCH 接口请求前数据处理回调 */
65
- patchReqMap?: RequestMapFunction<RequestData>;
66
- /** PATCH 接口请求结果数据处理回调 */
67
- patchResMap?: MapFunction;
68
- /** DELETE 接口请求前数据处理回调 */
69
- deleteReqMap?: RequestMapFunction<JSONObject>;
70
- /** DELETE 接口请求结果数据处理回调 */
71
- deleteResMap?: MapFunction;
72
- /** DELETE 批量删除 接口请求前数据处理回调 */
73
- multipleDeleteReqMap?: RequestMapFunction<JSONObject>;
74
- /** DELETE 批量删除 接口请求结果数据处理回调 */
75
- multipleDeleteResMap?: MapFunction;
76
-
77
- /** 查询选项 */
78
- arrOptions?: ArrOptions;
79
- }
80
-
81
- /**
82
- * 查询选项
83
- */
84
- export interface ArrOptions {
85
- /** 字符串字段是否开启模糊匹配 */
86
- fuzzy?: boolean;
87
- /** 模糊匹配时是否忽略大小写 */
88
- ignoreCase?: boolean;
89
- }
90
-
91
- /**
92
- * 删除请求配置接口
93
- */
94
- export interface ArrayDeleteConfig {
95
- /** axios delete url 参数 */
96
- params?: Record<string, any>;
97
- /** axios delete data 参数 */
98
- data?: Record<string, any>;
99
- /** 其他 axios delete 配置 */
100
- [key: string]: any;
101
- }
102
-
103
- /**
104
- * 错误处理选项接口
105
- */
106
- export interface HandleMsgOptions {
107
- /** 是否使用 response.statusText 作为兜底 msg */
108
- useStatusText?: boolean;
109
- }
110
-
111
- /**
112
- * 批量删除结果接口
113
- */
114
- export interface MultipleDeleteResult {
115
- /** 成功删除的 ID 列表 */
116
- sucList: any[];
117
- /** 失败删除的 ID 列表 */
118
- failList: any[];
119
- }
120
-
121
- /**
122
- * ArrayDataModel 本地数据 DataModel
123
- * @template T - 数据类型
124
- */
125
- class ArrayDataModel<T = any> extends ArrayUtils<T> {
126
- /** 请求 url 替换的额外参数 */
127
- ctx: Record<string, any>;
128
- /** GET 请求的参数 */
129
- query: QueryParams;
130
-
131
- /** POST 接口地址 */
132
- createApi?: string;
133
- /** POST 接口提交前的数据处理回调 */
134
- createMap?: MapFunction;
135
- /** GET 详情 接口地址 */
136
- getApi?: string;
137
- /** GET 详情 接口返回后的数据处理回调 */
138
- getMap?: MapFunction;
139
- /** GET 列表 接口地址 */
140
- getListApi?: string;
141
- /** GET 列表 接口返回后的数据处理回调 */
142
- getListMap?: MapFunction;
143
- /** GET 列表 接口回调,用于自定义列表请求接口 */
144
- getListFunc?: GetListFunc<T>;
145
- /** PUT 接口地址 */
146
- updateApi?: string;
147
- /** PUT 接口提交前的数据处理回调 */
148
- updateMap?: MapFunction;
149
- /** PATCH 接口地址 */
150
- patchApi?: string;
151
- /** PATCH 接口提交前的数据处理回调 */
152
- patchMap?: MapFunction;
153
- /** DELETE 接口地址 */
154
- deleteApi?: string;
155
- /** DELETE 批量删除 接口地址 */
156
- multipleDeleteApi?: string;
157
-
158
- /** GET 列表 接口请求前数据处理回调 */
159
- getListReqMap?: RequestMapFunction<QueryParams>;
160
- /** GET 列表 接口请求结果数据处理回调 */
161
- getListResMap?: MapFunction;
162
- /** GET 详情 接口请求前数据处理回调 */
163
- getReqMap?: RequestMapFunction<QueryParams>;
164
- /** GET 详情 接口请求结果数据处理回调 */
165
- getResMap?: MapFunction;
166
- /** POST 接口请求前数据处理回调 */
167
- createReqMap?: RequestMapFunction<RequestData>;
168
- /** POST 接口请求结果数据处理回调 */
169
- createResMap?: MapFunction;
170
- /** PUT 接口请求前数据处理回调 */
171
- updateReqMap?: RequestMapFunction<RequestData>;
172
- /** PUT 接口请求结果数据处理回调 */
173
- updateResMap?: MapFunction;
174
- /** PATCH 接口请求前数据处理回调 */
175
- patchReqMap?: RequestMapFunction<RequestData>;
176
- /** PATCH 接口请求结果数据处理回调 */
177
- patchResMap?: MapFunction;
178
- /** DELETE 接口请求前数据处理回调 */
179
- deleteReqMap?: RequestMapFunction<JSONObject>;
180
- /** DELETE 接口请求结果数据处理回调 */
181
- deleteResMap?: MapFunction;
182
- /** DELETE 批量删除 接口请求前数据处理回调 */
183
- multipleDeleteReqMap?: RequestMapFunction<JSONObject>;
184
- /** DELETE 批量删除 接口请求结果数据处理回调 */
185
- multipleDeleteResMap?: MapFunction;
186
-
187
- /** 查询选项 */
188
- private _arrOptions?: ArrOptions;
189
-
190
- constructor(params: ArrayDataModelOptions<T> = {} as ArrayDataModelOptions<T>) {
191
- super(params);
192
- const {
193
- ctx,
194
- query,
195
- createApi,
196
- createMap,
197
- getApi,
198
- getMap,
199
- getListApi,
200
- getListMap,
201
- getListFunc,
202
- updateApi,
203
- updateMap,
204
- patchApi,
205
- patchMap,
206
- deleteApi,
207
- multipleDeleteApi,
208
- } = params;
209
-
210
- this.ctx = ctx || {};
211
- this.query = query || {};
212
-
213
- this.createApi = createApi;
214
- this.createMap = createMap;
215
- this.getApi = getApi;
216
- this.getMap = getMap;
217
- this.getListApi = getListApi;
218
- this.getListMap = getListMap;
219
- this.getListFunc = getListFunc;
220
- this.updateApi = updateApi;
221
- this.updateMap = updateMap;
222
- this.patchApi = patchApi;
223
- this.patchMap = patchMap;
224
- this.deleteApi = deleteApi;
225
- this.multipleDeleteApi = multipleDeleteApi;
226
-
227
- const {
228
- getListReqMap,
229
- getListResMap,
230
- getReqMap,
231
- getResMap,
232
- createReqMap,
233
- createResMap,
234
- updateReqMap,
235
- updateResMap,
236
- patchReqMap,
237
- patchResMap,
238
- deleteReqMap,
239
- deleteResMap,
240
- multipleDeleteReqMap,
241
- multipleDeleteResMap,
242
- arrOptions,
243
- } = params || {};
244
-
245
- this.getListReqMap = getListReqMap;
246
- this.getListResMap = getListResMap;
247
- this.getReqMap = getReqMap;
248
- this.getResMap = getResMap;
249
- this.createReqMap = createReqMap;
250
- this.createResMap = createResMap;
251
- this.updateReqMap = updateReqMap;
252
- this.updateResMap = updateResMap;
253
- this.patchReqMap = patchReqMap;
254
- this.patchResMap = patchResMap;
255
- this.deleteReqMap = deleteReqMap;
256
- this.deleteResMap = deleteResMap;
257
- this.multipleDeleteReqMap = multipleDeleteReqMap;
258
- this.multipleDeleteResMap = multipleDeleteResMap;
259
- this._arrOptions = arrOptions;
260
- }
261
-
262
- /**
263
- * GET 详情请求
264
- * @param q query 参数
265
- * @returns Promise<T>
266
- */
267
- async get(q: QueryParams = {}): Promise<T> {
268
- let query = merge({}, this.query, q);
269
- query = pickBy(query, (val) => !isNil(val) && val !== "");
270
-
271
- if (this.getReqMap) {
272
- query = await this.getReqMap(query);
273
- }
274
-
275
- return new Promise((resolve) => {
276
- let res = this.findItem(query, this._arrOptions);
277
- if (res && this.getMap) {
278
- res = this.getMap(res);
279
- }
280
- if (res && this.getResMap) {
281
- res = this.getResMap(res);
282
- }
283
- resolve(res);
284
- });
285
- }
286
-
287
- /**
288
- * GET 列表请求
289
- * @param q query 参数
290
- * @returns Promise<FindListResult<T>>
291
- */
292
- async getList(q: QueryParams = {}): Promise<FindListResult<T>> {
293
- let query = merge({}, this.query, q);
294
- query = pickBy(query, (val) => !isNil(val) && val !== "");
295
-
296
- if (this.getListReqMap) {
297
- query = await this.getListReqMap(query);
298
- }
299
-
300
- let resultList: FindListResult<T>;
301
- if (this.getListFunc) {
302
- resultList = await this.getListFunc(query);
303
- } else {
304
- resultList = await this.findListByQuery(query, this._arrOptions);
305
- }
306
-
307
- const getListMap = this.getListMap;
308
- if (getListMap) {
309
- resultList.list = resultList?.list?.map((record) => getListMap(record));
310
- }
311
-
312
- const getListResMap = this.getListResMap;
313
- if (getListResMap) {
314
- resultList = getListResMap(resultList);
315
- }
316
-
317
- return resultList;
318
- }
319
-
320
- /**
321
- * POST 请求
322
- * @param params 参数
323
- * @returns Promise<Record<string, any>>
324
- */
325
- create(params: RequestData | FormData): Promise<Record<string, any>> {
326
- return new Promise(async (resolve, reject) => {
327
- const _params = await this.handleInputParams(params, this.createReqMap);
328
- const res = this.pushItem(_params);
329
- this.handleRes(res, resolve, reject, { resMap: this.createResMap });
330
- });
331
- }
332
-
333
- /**
334
- * PUT 请求
335
- * @param params 参数
336
- * @returns Promise<Record<string, any>>
337
- */
338
- update(params: RequestData | FormData): Promise<Record<string, any>> {
339
- return new Promise(async (resolve, reject) => {
340
- const _params = await this.handleInputParams(params, this.updateReqMap);
341
- const res = this.replaceItem(_params as T);
342
- this.handleRes(res, resolve, reject, { resMap: this.updateResMap });
343
- });
344
- }
345
-
346
- /**
347
- * PATCH 请求
348
- * @param params 参数
349
- * @returns Promise<Record<string, any>>
350
- */
351
- patch(params: RequestData | FormData): Promise<Record<string, any>> {
352
- return new Promise(async (resolve, reject) => {
353
- const _params = await this.handleInputParams(params, this.patchReqMap);
354
- const res = this.updateItemValue(_params);
355
- this.handleRes(res, resolve, reject, { resMap: this.patchResMap });
356
- });
357
- }
358
-
359
- /**
360
- * 删除接口
361
- * @param config axios.delete config 参数
362
- * @param config.params axios.delete url 参数
363
- * @param config.data axios.delete data 参数
364
- * @param ctx url 替换的额外参数
365
- * @returns Promise<Record<string, any>>
366
- */
367
- delete(config?: ArrayDeleteConfig, ctx?: Record<string, any>): Promise<Record<string, any>> {
368
- let _config = cloneDeep(config) || {};
369
- if (this.deleteReqMap) {
370
- _config = this.deleteReqMap(_config);
371
- }
372
- return new Promise((resolve, reject) => {
373
- const { _idKey } = this;
374
- const id = (config as any)?.[_idKey] || config?.params?.[_idKey] || config?.data?.[_idKey] || ctx?.[_idKey];
375
- const res = this.delItem(id);
376
- this.handleRes(res, resolve, reject, { resMap: this.deleteResMap });
377
- });
378
- }
379
-
380
- /**
381
- * 批量删除接口
382
- * @param config axios.delete config 参数
383
- * @param config.params axios.delete url 参数
384
- * @param config.data axios.delete data 参数
385
- * @param ctx url 替换的额外参数
386
- * @returns Promise<MultipleDeleteResult>
387
- */
388
- multipleDelete(config?: ArrayDeleteConfig, ctx?: Record<string, any>): Promise<MultipleDeleteResult> {
389
- let _config = cloneDeep(config) || {};
390
- if (this.multipleDeleteReqMap) {
391
- _config = this.multipleDeleteReqMap(_config);
392
- }
393
- return new Promise((resolve, reject) => {
394
- const { _idKey } = this;
395
- let ids = (config as any)?.[_idKey] || config?.params?.[_idKey] || config?.data?.[_idKey] || ctx?.[_idKey];
396
-
397
- if (typeof ids === "string") {
398
- ids = ids.split(",");
399
- }
400
-
401
- if (Array.isArray(ids)) {
402
- const sucList: any[] = [];
403
- const failList: any[] = [];
404
- ids.forEach((id: any) => {
405
- try {
406
- const res = this.delItem(id);
407
- if (res === STATE_CODE.SUC) {
408
- sucList.push(id);
409
- } else {
410
- failList.push(id);
411
- }
412
- } catch (error) {
413
- console.log("error", error);
414
- }
415
- });
416
- if (sucList.length > 0) {
417
- let _res: MultipleDeleteResult = { sucList, failList };
418
- if (this.multipleDeleteResMap) {
419
- _res = this.multipleDeleteResMap(_res);
420
- }
421
- resolve(_res);
422
- } else {
423
- reject({ failList });
424
- }
425
- return;
426
- }
427
-
428
- reject({});
429
- });
430
- }
431
-
432
- /**
433
- * 处理传入的数据
434
- * @param params 参数
435
- * @param reqMapFn 请求前处理函数
436
- * @returns 处理后的参数
437
- */
438
- async handleInputParams(
439
- params: any,
440
- reqMapFn?: (params: Record<string, any>, originalParams?: any) => Record<string, any>,
441
- ): Promise<Partial<T> & Record<string, any>> {
442
- let _params = cloneDeep(params) as Partial<T> & Record<string, any>;
443
- if (reqMapFn) {
444
- _params = (await reqMapFn(_params, params)) as Partial<T> & Record<string, any>;
445
- }
446
- // TODO: FormData 文件存储?
447
- // if (params instanceof FormData) {
448
- // _params = objToFormData(_params);
449
- // }
450
- return _params;
451
- }
452
-
453
- /**
454
- * 处理响应结果
455
- * @param response 响应对象
456
- * @param resolve 成功回调
457
- * @param reject 失败回调
458
- */
459
- handleRes(res: any, resolve: (res: any) => void, reject: (err: any) => void, opt?): void {
460
- const { resMap } = opt || {};
461
- if (res === STATE_CODE.SUC) {
462
- let _res: Record<string, any> = {};
463
- if (resMap) {
464
- _res = resMap(_res);
465
- }
466
- resolve(_res);
467
- } else {
468
- reject({
469
- code: res,
470
- _message: errMsg[res] || "未知错误",
471
- _msg: errMsg[res] || "未知错误",
472
- });
473
- }
474
- }
475
- }
476
-
477
- export { ArrayDataModel };
478
-
479
- export default ArrayDataModel;