@hzab/data-model 2.0.0 → 2.0.1-alpha.0

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.
package/src/data-model.ts CHANGED
@@ -1,850 +1,850 @@
1
- import _ from "lodash";
2
-
3
- import { axios, isCancel } from "./axios";
4
-
5
- import {
6
- objToFormData,
7
- formDataToObj,
8
- _$Temp,
9
- setDefaultAxios,
10
- setDefaultErrMsg,
11
- setNetworkErrMsg,
12
- checkNetwork,
13
- } from "./utils";
14
-
15
- import {
16
- JSONObject,
17
- QueryParams,
18
- RequestData,
19
- ResponseData,
20
- ResData,
21
- AxiosConfig,
22
- MapFunction,
23
- RequestMapFunction,
24
- GetListResult,
25
- GetListFunc,
26
- HandleResponseFunc,
27
- ApiError,
28
- } from "./type";
29
-
30
- /**
31
- * DataModel 构造函数参数接口
32
- */
33
- export interface DataModelOptions<R = any> {
34
- /** 请求 url 替换的额外参数 */
35
- ctx?: Record<string, any>;
36
- /** GET 请求的参数 */
37
- query?: QueryParams;
38
-
39
- /** POST 接口地址 */
40
- createApi?: string;
41
- /** POST 接口提交前的数据处理回调 */
42
- createMap?: MapFunction;
43
- /** GET 详情 接口地址 */
44
- getApi?: string;
45
- /** GET 详情 接口返回后的数据处理回调 */
46
- getMap?: MapFunction;
47
- /** GET 列表 接口地址 */
48
- getListApi?: string;
49
- /** GET 列表 接口返回后的数据处理回调 */
50
- getListMap?: MapFunction;
51
- /** GET 列表 接口回调,用于自定义列表请求接口 */
52
- getListFunc?: GetListFunc<R>;
53
- /** PUT 接口地址 */
54
- updateApi?: string;
55
- /** PUT 接口提交前的数据处理回调 */
56
- updateMap?: MapFunction;
57
- /** PATCH 接口地址 */
58
- patchApi?: string;
59
- /** PATCH 接口提交前的数据处理回调 */
60
- patchMap?: MapFunction;
61
- /** DELETE 接口地址 */
62
- deleteApi?: string;
63
- /** DELETE 批量删除 接口地址 */
64
- multipleDeleteApi?: string;
65
-
66
- /** GET 列表 接口请求前数据处理回调 */
67
- getListReqMap?: RequestMapFunction<QueryParams>;
68
- /** GET 列表 接口请求结果数据处理回调 */
69
- getListResMap?: MapFunction;
70
- /** GET 详情 接口请求前数据处理回调 */
71
- getReqMap?: RequestMapFunction<QueryParams>;
72
- /** GET 详情 接口请求结果数据处理回调 */
73
- getResMap?: MapFunction;
74
- /** POST 接口请求前数据处理回调 */
75
- createReqMap?: RequestMapFunction<RequestData>;
76
- /** POST 接口请求结果数据处理回调 */
77
- createResMap?: MapFunction;
78
- /** PUT 接口请求前数据处理回调 */
79
- updateReqMap?: RequestMapFunction<RequestData>;
80
- /** PUT 接口请求结果数据处理回调 */
81
- updateResMap?: MapFunction;
82
- /** PATCH 接口请求前数据处理回调 */
83
- patchReqMap?: RequestMapFunction<RequestData>;
84
- /** PATCH 接口请求结果数据处理回调 */
85
- patchResMap?: MapFunction;
86
- /** DELETE 接口请求前数据处理回调 */
87
- deleteReqMap?: RequestMapFunction<JSONObject>;
88
- /** DELETE 接口请求结果数据处理回调 */
89
- deleteResMap?: MapFunction;
90
- /** DELETE 批量删除 接口请求前数据处理回调 */
91
- multipleDeleteReqMap?: RequestMapFunction<JSONObject>;
92
- /** DELETE 批量删除 接口请求结果数据处理回调 */
93
- multipleDeleteResMap?: MapFunction;
94
-
95
- /** 统一 response 回调,用于处理定制 response 格式 */
96
- handleResponse?: HandleResponseFunc;
97
-
98
- /** 请求的 axios 实例 */
99
- axios?: typeof axios;
100
- /** axios 配置 */
101
- axiosConf?: AxiosConfig;
102
-
103
- /** GET 列表接口 axios 配置 */
104
- getListAxiosConf?: AxiosConfig;
105
- /** GET 详情接口 axios 配置 */
106
- getAxiosConf?: AxiosConfig;
107
- /** POST 接口 axios 配置 */
108
- createAxiosConf?: AxiosConfig;
109
- /** PUT 接口 axios 配置 */
110
- updateAxiosConf?: AxiosConfig;
111
- /** PATCH 接口 axios 配置 */
112
- patchAxiosConf?: AxiosConfig;
113
- /** DELETE 接口 axios 配置 */
114
- deleteAxiosConf?: AxiosConfig;
115
- /** DELETE 批量删除接口 axios 配置 */
116
- multipleDeleteAxiosConf?: AxiosConfig;
117
-
118
- /** 是否返回完整的接口数据(response.data) */
119
- isResponseData?: boolean;
120
- /** 是否直接返回 response */
121
- isResponse?: boolean;
122
- }
123
-
124
- /**
125
- * 删除请求配置接口
126
- */
127
- export interface DeleteConfig {
128
- /** axios delete url 参数 */
129
- params?: JSONObject;
130
- /** axios delete data 参数 */
131
- data?: JSONObject;
132
- /** 其他 axios delete 配置 */
133
- [key: string]: any;
134
- }
135
-
136
- /**
137
- * 获取 API 地址的选项接口
138
- */
139
- export interface GetApiUrlOptions {
140
- /** 请求来源标识 */
141
- from?: string;
142
- [key: string]: any;
143
- }
144
-
145
- /**
146
- * 错误处理选项接口
147
- */
148
- export interface HandleMsgOptions {
149
- /** 是否使用 response.statusText 作为兜底 msg */
150
- useStatusText?: boolean;
151
- }
152
-
153
- /**
154
- * DataModel 类
155
- * 用于封装常用的 CRUD 请求方法
156
- */
157
- class DataModel<T = any, R = Record<string, any>> {
158
- /** 是否返回完整的接口数据(response.data) */
159
- isResponseData: boolean;
160
- /** 是否直接返回 response */
161
- isResponse: boolean;
162
- /** 统一 response 回调,用于处理定制 response 格式 */
163
- handleResponse?: HandleResponseFunc;
164
-
165
- /** 请求 url 替换的额外参数 */
166
- ctx: Record<string, any>;
167
- /** GET 请求的参数 */
168
- query: QueryParams;
169
-
170
- /** POST 接口地址 */
171
- createApi?: string;
172
- /** POST 接口提交前的数据处理回调 */
173
- createMap?: MapFunction;
174
- /** GET 详情 接口地址 */
175
- getApi?: string;
176
- /** GET 详情 接口返回后的数据处理回调 */
177
- getMap?: MapFunction;
178
- /** GET 列表 接口地址 */
179
- getListApi?: string;
180
- /** GET 列表 接口返回后的数据处理回调 */
181
- getListMap?: MapFunction;
182
- /** GET 列表 接口回调,用于自定义列表请求接口 */
183
- getListFunc?: GetListFunc<T>;
184
- /** PUT 接口地址 */
185
- updateApi?: string;
186
- /** PUT 接口提交前的数据处理回调 */
187
- updateMap?: MapFunction;
188
- /** PATCH 接口地址 */
189
- patchApi?: string;
190
- /** PATCH 接口提交前的数据处理回调 */
191
- patchMap?: MapFunction;
192
- /** DELETE 接口地址 */
193
- deleteApi?: string;
194
- /** DELETE 批量删除 接口地址 */
195
- multipleDeleteApi?: string;
196
-
197
- /** GET 列表 接口请求前数据处理回调 */
198
- getListReqMap?: RequestMapFunction<QueryParams>;
199
- /** GET 列表 接口请求结果数据处理回调 */
200
- getListResMap?: MapFunction;
201
- /** GET 详情 接口请求前数据处理回调 */
202
- getReqMap?: RequestMapFunction<QueryParams>;
203
- /** GET 详情 接口请求结果数据处理回调 */
204
- getResMap?: MapFunction;
205
- /** POST 接口请求前数据处理回调 */
206
- createReqMap?: RequestMapFunction<RequestData>;
207
- /** POST 接口请求结果数据处理回调 */
208
- createResMap?: MapFunction;
209
- /** PUT 接口请求前数据处理回调 */
210
- updateReqMap?: RequestMapFunction<RequestData>;
211
- /** PUT 接口请求结果数据处理回调 */
212
- updateResMap?: MapFunction;
213
- /** PATCH 接口请求前数据处理回调 */
214
- patchReqMap?: RequestMapFunction<RequestData>;
215
- /** PATCH 接口请求结果数据处理回调 */
216
- patchResMap?: MapFunction;
217
- /** DELETE 接口请求前数据处理回调 */
218
- deleteReqMap?: RequestMapFunction<JSONObject>;
219
- /** DELETE 接口请求结果数据处理回调 */
220
- deleteResMap?: MapFunction;
221
- /** DELETE 批量删除 接口请求前数据处理回调 */
222
- multipleDeleteReqMap?: RequestMapFunction<JSONObject>;
223
- /** DELETE 批量删除 接口请求结果数据处理回调 */
224
- multipleDeleteResMap?: MapFunction;
225
-
226
- /** 请求的 axios 实例 */
227
- axios: typeof axios;
228
- /** axios 配置 */
229
- axiosConf: AxiosConfig;
230
-
231
- /** GET 列表接口 axios 配置 */
232
- getListAxiosConf?: AxiosConfig;
233
- /** GET 详情接口 axios 配置 */
234
- getAxiosConf?: AxiosConfig;
235
- /** POST 接口 axios 配置 */
236
- createAxiosConf?: AxiosConfig;
237
- /** PUT 接口 axios 配置 */
238
- updateAxiosConf?: AxiosConfig;
239
- /** PATCH 接口 axios 配置 */
240
- patchAxiosConf?: AxiosConfig;
241
- /** DELETE 接口 axios 配置 */
242
- deleteAxiosConf?: AxiosConfig;
243
- /** DELETE 批量删除接口 axios 配置 */
244
- multipleDeleteAxiosConf?: AxiosConfig;
245
-
246
- constructor(params: DataModelOptions<T>) {
247
- const {
248
- ctx,
249
- query,
250
- createApi,
251
- createMap,
252
- getApi,
253
- getMap,
254
- getListApi,
255
- getListMap,
256
- handleResponse,
257
- getListFunc,
258
- updateApi,
259
- updateMap,
260
- patchApi,
261
- patchMap,
262
- deleteApi,
263
- multipleDeleteApi,
264
- // 是否返回完整的接口数据(response.data)
265
- isResponseData,
266
- // 是否直接返回 response
267
- isResponse,
268
- } = params;
269
-
270
- /** 是否返回完整的接口数据(response.data) */
271
- this.isResponseData = !!isResponseData;
272
- /** 是否直接返回 response */
273
- this.isResponse = !!isResponse;
274
- /** 统一 response 回调,用于处理定制 response 格式 */
275
- this.handleResponse = handleResponse;
276
-
277
- /** 请求 url 替换的额外参数 */
278
- this.ctx = ctx || {};
279
- /** GET 请求的参数 */
280
- this.query = query || {};
281
-
282
- /** POST 接口地址 */
283
- this.createApi = createApi;
284
- /** POST 接口提交前的数据处理回调 */
285
- this.createMap = createMap;
286
- /** GET 详情 接口地址 */
287
- this.getApi = getApi;
288
- /** GET 详情 接口返回后的数据处理回调 */
289
- this.getMap = getMap;
290
- /** GET 列表 接口地址 */
291
- this.getListApi = getListApi;
292
- /** GET 列表 接口返回后的数据处理回调 */
293
- this.getListMap = getListMap;
294
- /** GET 列表 接口回调,用于自定义列表请求接口。query => ({list: [], pagination: { total: 0 }}) 优先级高于 getListApi */
295
- this.getListFunc = getListFunc;
296
- /** PUT 接口地址 */
297
- this.updateApi = updateApi;
298
- /** PUT 接口提交前的数据处理回调 */
299
- this.updateMap = updateMap;
300
- /** PATCH 接口地址 */
301
- this.patchApi = patchApi;
302
- /** PATCH 接口提交前的数据处理回调 */
303
- this.patchMap = patchMap;
304
- /** DELETE 接口地址 */
305
- this.deleteApi = deleteApi;
306
- /** DELETE 批量删除 接口地址 */
307
- this.multipleDeleteApi = multipleDeleteApi;
308
-
309
- const {
310
- getListReqMap,
311
- getListResMap,
312
- getReqMap,
313
- getResMap,
314
- createReqMap,
315
- createResMap,
316
- updateReqMap,
317
- updateResMap,
318
- patchReqMap,
319
- patchResMap,
320
- deleteReqMap,
321
- deleteResMap,
322
- multipleDeleteReqMap,
323
- multipleDeleteResMap,
324
- } = params || {};
325
-
326
- /** GET 列表 接口请求前数据处理回调 */
327
- this.getListReqMap = getListReqMap;
328
- /** GET 列表 接口请求结果数据处理回调 */
329
- this.getListResMap = getListResMap;
330
- /** GET 详情 接口请求前数据处理回调 */
331
- this.getReqMap = getReqMap;
332
- /** GET 详情 接口请求结果数据处理回调 */
333
- this.getResMap = getResMap;
334
- /** POST 接口请求前数据处理回调 */
335
- this.createReqMap = createReqMap;
336
- /** POST 接口请求结果数据处理回调 */
337
- this.createResMap = createResMap;
338
- /** PUT 接口请求前数据处理回调 */
339
- this.updateReqMap = updateReqMap;
340
- /** PUT 接口请求结果数据处理回调 */
341
- this.updateResMap = updateResMap;
342
- /** PATCH 接口请求前数据处理回调 */
343
- this.patchReqMap = patchReqMap;
344
- /** PATCH 接口请求结果数据处理回调 */
345
- this.patchResMap = patchResMap;
346
- /** DELETE 接口请求前数据处理回调 */
347
- this.deleteReqMap = deleteReqMap;
348
- /** DELETE 接口请求结果数据处理回调 */
349
- this.deleteResMap = deleteResMap;
350
- /** DELETE 批量删除 接口请求前数据处理回调 */
351
- this.multipleDeleteReqMap = multipleDeleteReqMap;
352
- /** DELETE 批量删除 接口请求结果数据处理回调 */
353
- this.multipleDeleteResMap = multipleDeleteResMap;
354
-
355
- // axios 相关配置
356
- const {
357
- axios: as,
358
- axiosConf,
359
- getListAxiosConf,
360
- getAxiosConf,
361
- createAxiosConf,
362
- updateAxiosConf,
363
- patchAxiosConf,
364
- deleteAxiosConf,
365
- multipleDeleteAxiosConf,
366
- } = params || {};
367
-
368
- /** 请求的 axios 实例 */
369
- this.axios = as || _$Temp.axios || axios;
370
- /** axios 配置 */
371
- this.axiosConf = axiosConf || {};
372
-
373
- /** GET 列表接口 axios 配置 */
374
- this.getListAxiosConf = getListAxiosConf;
375
- /** GET 详情接口 axios 配置 */
376
- this.getAxiosConf = getAxiosConf;
377
- /** POST 接口 axios 配置 */
378
- this.createAxiosConf = createAxiosConf;
379
- /** PUT 接口 axios 配置 */
380
- this.updateAxiosConf = updateAxiosConf;
381
- /** PATCH 接口 axios 配置 */
382
- this.patchAxiosConf = patchAxiosConf;
383
- /** DELETE 接口 axios 配置 */
384
- this.deleteAxiosConf = deleteAxiosConf;
385
- /** DELETE 批量删除接口 axios 配置 */
386
- this.multipleDeleteAxiosConf = multipleDeleteAxiosConf;
387
- }
388
-
389
- /**
390
- * 获取请求 url 地址
391
- * @param api 接口地址 https://a.com/test/:oId/:uId
392
- * @param record 替换参数 { uId: 81 }
393
- * @param ctx url 替换的额外参数
394
- * @param opt 选项
395
- * @returns 处理后的 api 地址
396
- */
397
- getApiUrl(
398
- api: string | undefined,
399
- record: JSONObject = {},
400
- ctx: JSONObject = this.ctx,
401
- opt?: GetApiUrlOptions,
402
- ): string {
403
- const { from } = opt ?? {};
404
- if (!api) {
405
- const errMsg = `${from ?? ""} api 不能为空。`;
406
- console.error(`Error ${errMsg} 具体入参:api、record、ctx、opt:`, api, record, ctx, opt);
407
- throw new Error(errMsg);
408
- }
409
- let apiUrl = api;
410
- const params = _.merge({}, record, ctx);
411
- _.each(params, (value, key) => {
412
- if (!_.isString(value) || !_.isNumber(value) || _.isBoolean(value)) {
413
- apiUrl = apiUrl.replace(new RegExp(`:${key}$|:${key}(?=/)`), value);
414
- }
415
- });
416
- return apiUrl;
417
- }
418
-
419
- /**
420
- * GET 详情请求
421
- * @param q query 参数
422
- * @param ctx url 替换的额外参数
423
- * @param axiosConf axios 配置
424
- * @returns Promise<any>
425
- */
426
- get(q: QueryParams = {}, ctx: JSONObject = {}, axiosConf?: AxiosConfig): Promise<any> {
427
- let query = _.merge({}, this.query, q);
428
- query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
429
-
430
- if (this.getReqMap) {
431
- query = this.getReqMap(query);
432
- }
433
-
434
- return new Promise((resolve, reject) => {
435
- const apiUrl = this.getApiUrl(this.getApi, query, ctx, { from: "get" });
436
- this.axios
437
- .get(apiUrl, {
438
- ...this.axiosConf,
439
- ...this.getAxiosConf,
440
- ...axiosConf,
441
- params: query,
442
- })
443
- .then((response: ResponseData) => {
444
- this.handleRes(
445
- response,
446
- (res: ResData<R>) => {
447
- if (this.getMap) {
448
- res = this.getMap(res);
449
- }
450
- if (this.getResMap) {
451
- res = this.getResMap(res);
452
- }
453
- resolve(res);
454
- },
455
- reject,
456
- );
457
- })
458
- .catch((err) => this.errorHandler(err, reject));
459
- });
460
- }
461
-
462
- /**
463
- * GET 列表请求
464
- * @param q query 参数
465
- * @param ctx url 替换的额外参数
466
- * @param axiosConf axios 配置
467
- * @returns Promise<GetListResult<T>>
468
- */
469
- async getList(q: QueryParams = {}, ctx: JSONObject = {}, axiosConf?: AxiosConfig): Promise<GetListResult<T>> {
470
- let query = _.merge({}, this.query, q);
471
- query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
472
-
473
- if (this.getListReqMap) {
474
- query = this.getListReqMap(query);
475
- }
476
-
477
- let resultList: GetListResult<T> | null = null;
478
- if (this.getListFunc) {
479
- resultList = await this.getListFunc(query);
480
- } else {
481
- const getPro = new Promise<GetListResult<T>>((resolve, reject) => {
482
- const apiUrl = this.getApiUrl(this.getListApi, q, ctx, { from: "getList" });
483
- this.axios
484
- .get(apiUrl, {
485
- ...this.axiosConf,
486
- ...this.getListAxiosConf,
487
- ...axiosConf,
488
- params: query,
489
- })
490
- .then((response) => {
491
- this.handleRes(
492
- response,
493
- (res: GetListResult<T>) => {
494
- // data: { list: [], pagination: { current: 0, total: 1 } }
495
- resolve(res);
496
- },
497
- reject,
498
- );
499
- })
500
- .catch((err) => this.errorHandler(err, reject));
501
- });
502
- resultList = await getPro;
503
- }
504
- if (this.getListMap) {
505
- resultList.list = resultList.list.map((record) => this.getListMap(record));
506
- }
507
- if (this.getListResMap) {
508
- resultList = this.getListResMap(resultList);
509
- }
510
-
511
- return resultList;
512
- }
513
-
514
- /**
515
- * POST 请求
516
- * @param params 参数
517
- * @param ctx url 替换的额外参数
518
- * @param axiosConf axios 配置
519
- * @returns Promise<any>
520
- */
521
- create(params?: RequestData | FormData, ctx?: JSONObject, axiosConf?: AxiosConfig): Promise<any> {
522
- return new Promise((resolve, reject) => {
523
- const opt: AxiosConfig = {
524
- ...this.axiosConf,
525
- ...this.createAxiosConf,
526
- ...axiosConf,
527
- };
528
- let _params = _.cloneDeep(formDataToObj(params));
529
- if (this.createReqMap) {
530
- _params = this.createReqMap(_params, params);
531
- }
532
- const apiUrl = this.getApiUrl(this.createApi, _params, ctx, { from: "create" });
533
- if (params instanceof FormData) {
534
- opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
535
- _params = objToFormData(_params);
536
- }
537
- this.axios
538
- .post(apiUrl, _params, opt)
539
- .then((response: ResponseData) => {
540
- this.handleRes(
541
- response,
542
- (res) => {
543
- if (this.createResMap) {
544
- res = this.createResMap(res);
545
- }
546
- resolve(res);
547
- },
548
- reject,
549
- );
550
- })
551
- .catch((err) => this.errorHandler(err, reject));
552
- });
553
- }
554
-
555
- /**
556
- * PUT 请求
557
- * @param params 参数
558
- * @param ctx url 替换的额外参数
559
- * @param axiosConf axios 配置
560
- * @returns Promise<any>
561
- */
562
- update(params?: RequestData | FormData, ctx?: JSONObject, axiosConf?: AxiosConfig): Promise<any> {
563
- return new Promise((resolve, reject) => {
564
- const opt: AxiosConfig = { ...this.axiosConf, ...this.updateAxiosConf, ...axiosConf };
565
- let _params = _.cloneDeep(formDataToObj(params));
566
- if (this.updateReqMap) {
567
- _params = this.updateReqMap(_params, params);
568
- }
569
- const apiUrl = this.getApiUrl(this.updateApi, _params, ctx, { from: "update" });
570
- if (params instanceof FormData) {
571
- opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
572
- _params = objToFormData(_params);
573
- }
574
- this.axios
575
- .put(apiUrl, _params, opt)
576
- .then((response) => {
577
- this.handleRes(
578
- response,
579
- (res) => {
580
- if (this.updateResMap) {
581
- res = this.updateResMap(res);
582
- }
583
- resolve(res);
584
- },
585
- reject,
586
- );
587
- })
588
- .catch((err) => this.errorHandler(err, reject));
589
- });
590
- }
591
-
592
- /**
593
- * PATCH 请求
594
- * @param params 参数
595
- * @param ctx url 替换的额外参数
596
- * @param axiosConf axios 配置
597
- * @returns Promise<any>
598
- */
599
- patch(params?: RequestData | FormData, ctx?: JSONObject, axiosConf?: AxiosConfig): Promise<any> {
600
- return new Promise((resolve, reject) => {
601
- const opt: AxiosConfig = { ...this.axiosConf, ...this.patchAxiosConf, ...axiosConf };
602
- let _params = _.cloneDeep(formDataToObj(params));
603
- if (this.patchReqMap) {
604
- _params = this.patchReqMap(_params, params);
605
- }
606
- const apiUrl = this.getApiUrl(this.patchApi, _params, ctx, { from: "patch" });
607
- if (params instanceof FormData) {
608
- opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
609
- _params = objToFormData(_params);
610
- }
611
- this.axios
612
- .patch(apiUrl, _params, opt)
613
- .then((response) => {
614
- this.handleRes(
615
- response,
616
- (res) => {
617
- if (this.patchResMap) {
618
- res = this.patchResMap(res);
619
- }
620
- resolve(res);
621
- },
622
- reject,
623
- );
624
- })
625
- .catch((err) => this.errorHandler(err, reject));
626
- });
627
- }
628
-
629
- /**
630
- * 删除接口
631
- * @param config axios.delete config 参数
632
- * @param config.params axios.delete url 参数
633
- * @param config.data axios.delete data 参数
634
- * @param ctx url 替换的额外参数
635
- * @returns Promise<any>
636
- */
637
- delete(config?: DeleteConfig, ctx?: JSONObject): Promise<any> {
638
- let _config = _.cloneDeep(config) || {};
639
- if (this.deleteReqMap) {
640
- _config = this.deleteReqMap(_config);
641
- }
642
- return new Promise((resolve, reject) => {
643
- const apiUrl = this.getApiUrl(
644
- this.deleteApi,
645
- Object.assign(_.cloneDeep(_config), _config.params, _config.data),
646
- ctx,
647
- { from: "delete" },
648
- );
649
- this.axios
650
- .delete(apiUrl, { ...this.axiosConf, ...this.deleteAxiosConf, ..._config })
651
- .then((response) => {
652
- this.handleRes(
653
- response,
654
- (res) => {
655
- if (this.deleteResMap) {
656
- res = this.deleteResMap(res);
657
- }
658
- resolve(res);
659
- },
660
- reject,
661
- );
662
- })
663
- .catch((err) => this.errorHandler(err, reject));
664
- });
665
- }
666
-
667
- /**
668
- * 批量删除接口
669
- * @param config axios.delete config 参数
670
- * @param config.params axios.delete url 参数
671
- * @param config.data axios.delete data 参数
672
- * @param ctx url 替换的额外参数
673
- * @returns Promise<any>
674
- */
675
- multipleDelete(config?: DeleteConfig, ctx?: JSONObject): Promise<any> {
676
- let _config = _.cloneDeep(config) || {};
677
- if (this.multipleDeleteReqMap) {
678
- _config = this.multipleDeleteReqMap(_config);
679
- }
680
- return new Promise((resolve, reject) => {
681
- const apiUrl = this.getApiUrl(
682
- this.multipleDeleteApi,
683
- Object.assign(_.cloneDeep(_config), _config.params, _config.data),
684
- ctx,
685
- { from: "multipleDelete" },
686
- );
687
- this.axios
688
- .delete(apiUrl, { ...this.axiosConf, ...this.multipleDeleteAxiosConf, ..._config })
689
- .then((response) => {
690
- this.handleRes(
691
- response,
692
- (res: ResponseData) => {
693
- if (this.multipleDeleteResMap) {
694
- res = this.multipleDeleteResMap(res);
695
- }
696
- resolve(res);
697
- },
698
- reject,
699
- );
700
- })
701
- .catch((err) => this.errorHandler(err, reject));
702
- });
703
- }
704
-
705
- /**
706
- * 处理响应结果
707
- * @param response axios 响应对象
708
- * @param resolve 成功回调
709
- * @param reject 失败回调
710
- */
711
- handleRes(response: ResponseData, resolve: (res: any) => void, reject: (err: ApiError) => void) {
712
- if (isCancel(response)) {
713
- console.info("errorHandler isCancel", response);
714
- return;
715
- }
716
- if (this.isResponse) {
717
- resolve(response);
718
- return;
719
- }
720
- if (this.isResponseData) {
721
- resolve(response?.data ?? response);
722
- return;
723
- }
724
- if (typeof response !== "object") {
725
- reject(new Error("response not object") as ApiError);
726
- return;
727
- }
728
-
729
- let _res: ResponseData | ResData;
730
- _res = this.handleResponse ? this.handleResponse(response) : response;
731
-
732
- const isAxiosResponse = (obj: any): obj is ResponseData => {
733
- return obj && "status" in obj && "headers" in obj && "request" in obj;
734
- };
735
-
736
- if (isAxiosResponse(_res)) {
737
- _res = _res.data;
738
- }
739
-
740
- const { code, data } = _res as ResData;
741
- const message = this.handleMsg(response);
742
- if (code == 200) {
743
- const _data = data ?? {};
744
- if (_.isObject(_data)) {
745
- if (_data.content && _data.pageNumber && _data.total) {
746
- _data.list = _data.content;
747
- _data.pagination = { current: _data.pageNumber, total: _data.total };
748
- }
749
- // 前缀 _ 避免与 data 里已有的 message 冲突
750
- _data._msg = message;
751
- _data._message = message;
752
- }
753
- resolve(_data);
754
- } else {
755
- const error = new Error(message) as ApiError;
756
- error.code = code;
757
- error.response = response;
758
- error._msg = message;
759
- error._message = message;
760
- reject(error);
761
- }
762
- }
763
-
764
- /**
765
- * 错误处理器
766
- * @param err 错误对象
767
- * @param reject Promise reject 回调
768
- */
769
- errorHandler(err: any = {}, reject: (err: ApiError) => void) {
770
- if (isCancel(err)) {
771
- console.info("errorHandler isCancel", err);
772
- return;
773
- }
774
- if (this.isResponse) {
775
- reject(err);
776
- return;
777
- }
778
- if (this.isResponseData) {
779
- reject(err?.data ?? err);
780
- return;
781
- }
782
- const response = err?.response || err;
783
- if (response) {
784
- const message = this.handleMsg(response, { useStatusText: true });
785
- const error = new Error(message) as ApiError;
786
- error.code = response.status;
787
- error.response = response;
788
- if (message) {
789
- // 前缀 _ 避免与 data 里已有的 message 冲突
790
- error._message = message;
791
- error._msg = message;
792
- }
793
- return reject(error);
794
- }
795
- return reject(err ?? { _msg: _$Temp.networkErrMsg });
796
- }
797
-
798
- /**
799
- * 处理错误消息
800
- * @param response 响应对象
801
- * @param opt 选项
802
- * @returns 错误消息
803
- */
804
- handleMsg(
805
- response: any,
806
- opt: HandleMsgOptions = {
807
- // 是否使用 response.statusText 作为兜底 msg
808
- useStatusText: false,
809
- },
810
- ): string {
811
- const { useStatusText } = opt || {};
812
- let message =
813
- (response.data && (response.data.message || response.data.msg)) ||
814
- response.msg ||
815
- response.message ||
816
- this.getNetworkErrMsg(response);
817
-
818
- if (!message && useStatusText) {
819
- message = response.statusText;
820
- }
821
-
822
- return message || _$Temp.defaultErrMsg;
823
- }
824
-
825
- /**
826
- * 获取网络错误消息
827
- * @param httpCode HTTP 状态码
828
- * @returns 错误消息
829
- */
830
- getNetworkErrMsg(httpCode: string): string {
831
- const { networkErrMsg } = _$Temp;
832
- if (httpCode === "ERR_NETWORK") {
833
- return networkErrMsg;
834
- }
835
- return checkNetwork() ? "" : networkErrMsg;
836
- }
837
- }
838
-
839
- export {
840
- axios,
841
- checkNetwork,
842
- DataModel,
843
- formDataToObj,
844
- objToFormData,
845
- setDefaultAxios,
846
- setDefaultErrMsg,
847
- setNetworkErrMsg,
848
- };
849
-
850
- export default DataModel;
1
+ import _ from "lodash";
2
+
3
+ import { axios, isCancel } from "./axios";
4
+
5
+ import {
6
+ objToFormData,
7
+ formDataToObj,
8
+ _$Temp,
9
+ setDefaultAxios,
10
+ setDefaultErrMsg,
11
+ setNetworkErrMsg,
12
+ checkNetwork,
13
+ } from "./utils";
14
+
15
+ import {
16
+ JSONObject,
17
+ QueryParams,
18
+ RequestData,
19
+ ResponseData,
20
+ ResData,
21
+ AxiosConfig,
22
+ MapFunction,
23
+ RequestMapFunction,
24
+ GetListResult,
25
+ GetListFunc,
26
+ HandleResponseFunc,
27
+ ApiError,
28
+ } from "./type";
29
+
30
+ /**
31
+ * DataModel 构造函数参数接口
32
+ */
33
+ export interface DataModelOptions<R = any> {
34
+ /** 请求 url 替换的额外参数 */
35
+ ctx?: Record<string, any>;
36
+ /** GET 请求的参数 */
37
+ query?: QueryParams;
38
+
39
+ /** POST 接口地址 */
40
+ createApi?: string;
41
+ /** POST 接口提交前的数据处理回调 */
42
+ createMap?: MapFunction;
43
+ /** GET 详情 接口地址 */
44
+ getApi?: string;
45
+ /** GET 详情 接口返回后的数据处理回调 */
46
+ getMap?: MapFunction;
47
+ /** GET 列表 接口地址 */
48
+ getListApi?: string;
49
+ /** GET 列表 接口返回后的数据处理回调 */
50
+ getListMap?: MapFunction;
51
+ /** GET 列表 接口回调,用于自定义列表请求接口 */
52
+ getListFunc?: GetListFunc<R>;
53
+ /** PUT 接口地址 */
54
+ updateApi?: string;
55
+ /** PUT 接口提交前的数据处理回调 */
56
+ updateMap?: MapFunction;
57
+ /** PATCH 接口地址 */
58
+ patchApi?: string;
59
+ /** PATCH 接口提交前的数据处理回调 */
60
+ patchMap?: MapFunction;
61
+ /** DELETE 接口地址 */
62
+ deleteApi?: string;
63
+ /** DELETE 批量删除 接口地址 */
64
+ multipleDeleteApi?: string;
65
+
66
+ /** GET 列表 接口请求前数据处理回调 */
67
+ getListReqMap?: RequestMapFunction<QueryParams>;
68
+ /** GET 列表 接口请求结果数据处理回调 */
69
+ getListResMap?: MapFunction;
70
+ /** GET 详情 接口请求前数据处理回调 */
71
+ getReqMap?: RequestMapFunction<QueryParams>;
72
+ /** GET 详情 接口请求结果数据处理回调 */
73
+ getResMap?: MapFunction;
74
+ /** POST 接口请求前数据处理回调 */
75
+ createReqMap?: RequestMapFunction<RequestData>;
76
+ /** POST 接口请求结果数据处理回调 */
77
+ createResMap?: MapFunction;
78
+ /** PUT 接口请求前数据处理回调 */
79
+ updateReqMap?: RequestMapFunction<RequestData>;
80
+ /** PUT 接口请求结果数据处理回调 */
81
+ updateResMap?: MapFunction;
82
+ /** PATCH 接口请求前数据处理回调 */
83
+ patchReqMap?: RequestMapFunction<RequestData>;
84
+ /** PATCH 接口请求结果数据处理回调 */
85
+ patchResMap?: MapFunction;
86
+ /** DELETE 接口请求前数据处理回调 */
87
+ deleteReqMap?: RequestMapFunction<JSONObject>;
88
+ /** DELETE 接口请求结果数据处理回调 */
89
+ deleteResMap?: MapFunction;
90
+ /** DELETE 批量删除 接口请求前数据处理回调 */
91
+ multipleDeleteReqMap?: RequestMapFunction<JSONObject>;
92
+ /** DELETE 批量删除 接口请求结果数据处理回调 */
93
+ multipleDeleteResMap?: MapFunction;
94
+
95
+ /** 统一 response 回调,用于处理定制 response 格式 */
96
+ handleResponse?: HandleResponseFunc;
97
+
98
+ /** 请求的 axios 实例 */
99
+ axios?: typeof axios;
100
+ /** axios 配置 */
101
+ axiosConf?: AxiosConfig;
102
+
103
+ /** GET 列表接口 axios 配置 */
104
+ getListAxiosConf?: AxiosConfig;
105
+ /** GET 详情接口 axios 配置 */
106
+ getAxiosConf?: AxiosConfig;
107
+ /** POST 接口 axios 配置 */
108
+ createAxiosConf?: AxiosConfig;
109
+ /** PUT 接口 axios 配置 */
110
+ updateAxiosConf?: AxiosConfig;
111
+ /** PATCH 接口 axios 配置 */
112
+ patchAxiosConf?: AxiosConfig;
113
+ /** DELETE 接口 axios 配置 */
114
+ deleteAxiosConf?: AxiosConfig;
115
+ /** DELETE 批量删除接口 axios 配置 */
116
+ multipleDeleteAxiosConf?: AxiosConfig;
117
+
118
+ /** 是否返回完整的接口数据(response.data) */
119
+ isResponseData?: boolean;
120
+ /** 是否直接返回 response */
121
+ isResponse?: boolean;
122
+ }
123
+
124
+ /**
125
+ * 删除请求配置接口
126
+ */
127
+ export interface DeleteConfig {
128
+ /** axios delete url 参数 */
129
+ params?: JSONObject;
130
+ /** axios delete data 参数 */
131
+ data?: JSONObject;
132
+ /** 其他 axios delete 配置 */
133
+ [key: string]: any;
134
+ }
135
+
136
+ /**
137
+ * 获取 API 地址的选项接口
138
+ */
139
+ export interface GetApiUrlOptions {
140
+ /** 请求来源标识 */
141
+ from?: string;
142
+ [key: string]: any;
143
+ }
144
+
145
+ /**
146
+ * 错误处理选项接口
147
+ */
148
+ export interface HandleMsgOptions {
149
+ /** 是否使用 response.statusText 作为兜底 msg */
150
+ useStatusText?: boolean;
151
+ }
152
+
153
+ /**
154
+ * DataModel 类
155
+ * 用于封装常用的 CRUD 请求方法
156
+ */
157
+ class DataModel<T = any, R = Record<string, any>> {
158
+ /** 是否返回完整的接口数据(response.data) */
159
+ isResponseData: boolean;
160
+ /** 是否直接返回 response */
161
+ isResponse: boolean;
162
+ /** 统一 response 回调,用于处理定制 response 格式 */
163
+ handleResponse?: HandleResponseFunc;
164
+
165
+ /** 请求 url 替换的额外参数 */
166
+ ctx: Record<string, any>;
167
+ /** GET 请求的参数 */
168
+ query: QueryParams;
169
+
170
+ /** POST 接口地址 */
171
+ createApi?: string;
172
+ /** POST 接口提交前的数据处理回调 */
173
+ createMap?: MapFunction;
174
+ /** GET 详情 接口地址 */
175
+ getApi?: string;
176
+ /** GET 详情 接口返回后的数据处理回调 */
177
+ getMap?: MapFunction;
178
+ /** GET 列表 接口地址 */
179
+ getListApi?: string;
180
+ /** GET 列表 接口返回后的数据处理回调 */
181
+ getListMap?: MapFunction;
182
+ /** GET 列表 接口回调,用于自定义列表请求接口 */
183
+ getListFunc?: GetListFunc<T>;
184
+ /** PUT 接口地址 */
185
+ updateApi?: string;
186
+ /** PUT 接口提交前的数据处理回调 */
187
+ updateMap?: MapFunction;
188
+ /** PATCH 接口地址 */
189
+ patchApi?: string;
190
+ /** PATCH 接口提交前的数据处理回调 */
191
+ patchMap?: MapFunction;
192
+ /** DELETE 接口地址 */
193
+ deleteApi?: string;
194
+ /** DELETE 批量删除 接口地址 */
195
+ multipleDeleteApi?: string;
196
+
197
+ /** GET 列表 接口请求前数据处理回调 */
198
+ getListReqMap?: RequestMapFunction<QueryParams>;
199
+ /** GET 列表 接口请求结果数据处理回调 */
200
+ getListResMap?: MapFunction;
201
+ /** GET 详情 接口请求前数据处理回调 */
202
+ getReqMap?: RequestMapFunction<QueryParams>;
203
+ /** GET 详情 接口请求结果数据处理回调 */
204
+ getResMap?: MapFunction;
205
+ /** POST 接口请求前数据处理回调 */
206
+ createReqMap?: RequestMapFunction<RequestData>;
207
+ /** POST 接口请求结果数据处理回调 */
208
+ createResMap?: MapFunction;
209
+ /** PUT 接口请求前数据处理回调 */
210
+ updateReqMap?: RequestMapFunction<RequestData>;
211
+ /** PUT 接口请求结果数据处理回调 */
212
+ updateResMap?: MapFunction;
213
+ /** PATCH 接口请求前数据处理回调 */
214
+ patchReqMap?: RequestMapFunction<RequestData>;
215
+ /** PATCH 接口请求结果数据处理回调 */
216
+ patchResMap?: MapFunction;
217
+ /** DELETE 接口请求前数据处理回调 */
218
+ deleteReqMap?: RequestMapFunction<JSONObject>;
219
+ /** DELETE 接口请求结果数据处理回调 */
220
+ deleteResMap?: MapFunction;
221
+ /** DELETE 批量删除 接口请求前数据处理回调 */
222
+ multipleDeleteReqMap?: RequestMapFunction<JSONObject>;
223
+ /** DELETE 批量删除 接口请求结果数据处理回调 */
224
+ multipleDeleteResMap?: MapFunction;
225
+
226
+ /** 请求的 axios 实例 */
227
+ axios: typeof axios;
228
+ /** axios 配置 */
229
+ axiosConf: AxiosConfig;
230
+
231
+ /** GET 列表接口 axios 配置 */
232
+ getListAxiosConf?: AxiosConfig;
233
+ /** GET 详情接口 axios 配置 */
234
+ getAxiosConf?: AxiosConfig;
235
+ /** POST 接口 axios 配置 */
236
+ createAxiosConf?: AxiosConfig;
237
+ /** PUT 接口 axios 配置 */
238
+ updateAxiosConf?: AxiosConfig;
239
+ /** PATCH 接口 axios 配置 */
240
+ patchAxiosConf?: AxiosConfig;
241
+ /** DELETE 接口 axios 配置 */
242
+ deleteAxiosConf?: AxiosConfig;
243
+ /** DELETE 批量删除接口 axios 配置 */
244
+ multipleDeleteAxiosConf?: AxiosConfig;
245
+
246
+ constructor(params: DataModelOptions<T>) {
247
+ const {
248
+ ctx,
249
+ query,
250
+ createApi,
251
+ createMap,
252
+ getApi,
253
+ getMap,
254
+ getListApi,
255
+ getListMap,
256
+ handleResponse,
257
+ getListFunc,
258
+ updateApi,
259
+ updateMap,
260
+ patchApi,
261
+ patchMap,
262
+ deleteApi,
263
+ multipleDeleteApi,
264
+ // 是否返回完整的接口数据(response.data)
265
+ isResponseData,
266
+ // 是否直接返回 response
267
+ isResponse,
268
+ } = params;
269
+
270
+ /** 是否返回完整的接口数据(response.data) */
271
+ this.isResponseData = !!isResponseData;
272
+ /** 是否直接返回 response */
273
+ this.isResponse = !!isResponse;
274
+ /** 统一 response 回调,用于处理定制 response 格式 */
275
+ this.handleResponse = handleResponse;
276
+
277
+ /** 请求 url 替换的额外参数 */
278
+ this.ctx = ctx || {};
279
+ /** GET 请求的参数 */
280
+ this.query = query || {};
281
+
282
+ /** POST 接口地址 */
283
+ this.createApi = createApi;
284
+ /** POST 接口提交前的数据处理回调 */
285
+ this.createMap = createMap;
286
+ /** GET 详情 接口地址 */
287
+ this.getApi = getApi;
288
+ /** GET 详情 接口返回后的数据处理回调 */
289
+ this.getMap = getMap;
290
+ /** GET 列表 接口地址 */
291
+ this.getListApi = getListApi;
292
+ /** GET 列表 接口返回后的数据处理回调 */
293
+ this.getListMap = getListMap;
294
+ /** GET 列表 接口回调,用于自定义列表请求接口。query => ({list: [], pagination: { total: 0 }}) 优先级高于 getListApi */
295
+ this.getListFunc = getListFunc;
296
+ /** PUT 接口地址 */
297
+ this.updateApi = updateApi;
298
+ /** PUT 接口提交前的数据处理回调 */
299
+ this.updateMap = updateMap;
300
+ /** PATCH 接口地址 */
301
+ this.patchApi = patchApi;
302
+ /** PATCH 接口提交前的数据处理回调 */
303
+ this.patchMap = patchMap;
304
+ /** DELETE 接口地址 */
305
+ this.deleteApi = deleteApi;
306
+ /** DELETE 批量删除 接口地址 */
307
+ this.multipleDeleteApi = multipleDeleteApi;
308
+
309
+ const {
310
+ getListReqMap,
311
+ getListResMap,
312
+ getReqMap,
313
+ getResMap,
314
+ createReqMap,
315
+ createResMap,
316
+ updateReqMap,
317
+ updateResMap,
318
+ patchReqMap,
319
+ patchResMap,
320
+ deleteReqMap,
321
+ deleteResMap,
322
+ multipleDeleteReqMap,
323
+ multipleDeleteResMap,
324
+ } = params || {};
325
+
326
+ /** GET 列表 接口请求前数据处理回调 */
327
+ this.getListReqMap = getListReqMap;
328
+ /** GET 列表 接口请求结果数据处理回调 */
329
+ this.getListResMap = getListResMap;
330
+ /** GET 详情 接口请求前数据处理回调 */
331
+ this.getReqMap = getReqMap;
332
+ /** GET 详情 接口请求结果数据处理回调 */
333
+ this.getResMap = getResMap;
334
+ /** POST 接口请求前数据处理回调 */
335
+ this.createReqMap = createReqMap;
336
+ /** POST 接口请求结果数据处理回调 */
337
+ this.createResMap = createResMap;
338
+ /** PUT 接口请求前数据处理回调 */
339
+ this.updateReqMap = updateReqMap;
340
+ /** PUT 接口请求结果数据处理回调 */
341
+ this.updateResMap = updateResMap;
342
+ /** PATCH 接口请求前数据处理回调 */
343
+ this.patchReqMap = patchReqMap;
344
+ /** PATCH 接口请求结果数据处理回调 */
345
+ this.patchResMap = patchResMap;
346
+ /** DELETE 接口请求前数据处理回调 */
347
+ this.deleteReqMap = deleteReqMap;
348
+ /** DELETE 接口请求结果数据处理回调 */
349
+ this.deleteResMap = deleteResMap;
350
+ /** DELETE 批量删除 接口请求前数据处理回调 */
351
+ this.multipleDeleteReqMap = multipleDeleteReqMap;
352
+ /** DELETE 批量删除 接口请求结果数据处理回调 */
353
+ this.multipleDeleteResMap = multipleDeleteResMap;
354
+
355
+ // axios 相关配置
356
+ const {
357
+ axios: as,
358
+ axiosConf,
359
+ getListAxiosConf,
360
+ getAxiosConf,
361
+ createAxiosConf,
362
+ updateAxiosConf,
363
+ patchAxiosConf,
364
+ deleteAxiosConf,
365
+ multipleDeleteAxiosConf,
366
+ } = params || {};
367
+
368
+ /** 请求的 axios 实例 */
369
+ this.axios = as || _$Temp.axios || axios;
370
+ /** axios 配置 */
371
+ this.axiosConf = axiosConf || {};
372
+
373
+ /** GET 列表接口 axios 配置 */
374
+ this.getListAxiosConf = getListAxiosConf;
375
+ /** GET 详情接口 axios 配置 */
376
+ this.getAxiosConf = getAxiosConf;
377
+ /** POST 接口 axios 配置 */
378
+ this.createAxiosConf = createAxiosConf;
379
+ /** PUT 接口 axios 配置 */
380
+ this.updateAxiosConf = updateAxiosConf;
381
+ /** PATCH 接口 axios 配置 */
382
+ this.patchAxiosConf = patchAxiosConf;
383
+ /** DELETE 接口 axios 配置 */
384
+ this.deleteAxiosConf = deleteAxiosConf;
385
+ /** DELETE 批量删除接口 axios 配置 */
386
+ this.multipleDeleteAxiosConf = multipleDeleteAxiosConf;
387
+ }
388
+
389
+ /**
390
+ * 获取请求 url 地址
391
+ * @param api 接口地址 https://a.com/test/:oId/:uId
392
+ * @param record 替换参数 { uId: 81 }
393
+ * @param ctx url 替换的额外参数
394
+ * @param opt 选项
395
+ * @returns 处理后的 api 地址
396
+ */
397
+ getApiUrl(
398
+ api: string | undefined,
399
+ record: JSONObject = {},
400
+ ctx: JSONObject = this.ctx,
401
+ opt?: GetApiUrlOptions,
402
+ ): string {
403
+ const { from } = opt ?? {};
404
+ if (!api) {
405
+ const errMsg = `${from ?? ""} api 不能为空。`;
406
+ console.error(`Error ${errMsg} 具体入参:api、record、ctx、opt:`, api, record, ctx, opt);
407
+ throw new Error(errMsg);
408
+ }
409
+ let apiUrl = api;
410
+ const params = _.merge({}, record, ctx);
411
+ _.each(params, (value, key) => {
412
+ if (!_.isString(value) || !_.isNumber(value) || _.isBoolean(value)) {
413
+ apiUrl = apiUrl.replace(new RegExp(`:${key}$|:${key}(?=/)`), value);
414
+ }
415
+ });
416
+ return apiUrl;
417
+ }
418
+
419
+ /**
420
+ * GET 详情请求
421
+ * @param q query 参数
422
+ * @param ctx url 替换的额外参数
423
+ * @param axiosConf axios 配置
424
+ * @returns Promise<any>
425
+ */
426
+ async get(q: QueryParams = {}, ctx: JSONObject = {}, axiosConf?: AxiosConfig): Promise<any> {
427
+ let query = _.merge({}, this.query, q);
428
+ query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
429
+
430
+ if (this.getReqMap) {
431
+ query = await this.getReqMap(query);
432
+ }
433
+
434
+ return new Promise((resolve, reject) => {
435
+ const apiUrl = this.getApiUrl(this.getApi, query, ctx, { from: "get" });
436
+ this.axios
437
+ .get(apiUrl, {
438
+ ...this.axiosConf,
439
+ ...this.getAxiosConf,
440
+ ...axiosConf,
441
+ params: query,
442
+ })
443
+ .then((response: ResponseData) => {
444
+ this.handleRes(
445
+ response,
446
+ (res: ResData<R>) => {
447
+ if (this.getMap) {
448
+ res = this.getMap(res);
449
+ }
450
+ if (this.getResMap) {
451
+ res = this.getResMap(res);
452
+ }
453
+ resolve(res);
454
+ },
455
+ reject,
456
+ );
457
+ })
458
+ .catch((err) => this.errorHandler(err, reject));
459
+ });
460
+ }
461
+
462
+ /**
463
+ * GET 列表请求
464
+ * @param q query 参数
465
+ * @param ctx url 替换的额外参数
466
+ * @param axiosConf axios 配置
467
+ * @returns Promise<GetListResult<T>>
468
+ */
469
+ async getList(q: QueryParams = {}, ctx: JSONObject = {}, axiosConf?: AxiosConfig): Promise<GetListResult<T>> {
470
+ let query = _.merge({}, this.query, q);
471
+ query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
472
+
473
+ if (this.getListReqMap) {
474
+ query = await this.getListReqMap(query);
475
+ }
476
+
477
+ let resultList: GetListResult<T> | null = null;
478
+ if (this.getListFunc) {
479
+ resultList = await this.getListFunc(query);
480
+ } else {
481
+ const getPro = new Promise<GetListResult<T>>((resolve, reject) => {
482
+ const apiUrl = this.getApiUrl(this.getListApi, q, ctx, { from: "getList" });
483
+ this.axios
484
+ .get(apiUrl, {
485
+ ...this.axiosConf,
486
+ ...this.getListAxiosConf,
487
+ ...axiosConf,
488
+ params: query,
489
+ })
490
+ .then((response) => {
491
+ this.handleRes(
492
+ response,
493
+ (res: GetListResult<T>) => {
494
+ // data: { list: [], pagination: { current: 0, total: 1 } }
495
+ resolve(res);
496
+ },
497
+ reject,
498
+ );
499
+ })
500
+ .catch((err) => this.errorHandler(err, reject));
501
+ });
502
+ resultList = await getPro;
503
+ }
504
+ if (this.getListMap) {
505
+ resultList.list = resultList.list.map((record) => this.getListMap(record));
506
+ }
507
+ if (this.getListResMap) {
508
+ resultList = this.getListResMap(resultList);
509
+ }
510
+
511
+ return resultList;
512
+ }
513
+
514
+ /**
515
+ * POST 请求
516
+ * @param params 参数
517
+ * @param ctx url 替换的额外参数
518
+ * @param axiosConf axios 配置
519
+ * @returns Promise<any>
520
+ */
521
+ create(params?: RequestData | FormData, ctx?: JSONObject, axiosConf?: AxiosConfig): Promise<any> {
522
+ return new Promise(async (resolve, reject) => {
523
+ const opt: AxiosConfig = {
524
+ ...this.axiosConf,
525
+ ...this.createAxiosConf,
526
+ ...axiosConf,
527
+ };
528
+ let _params = _.cloneDeep(formDataToObj(params));
529
+ if (this.createReqMap) {
530
+ _params = await this.createReqMap(_params, params);
531
+ }
532
+ const apiUrl = this.getApiUrl(this.createApi, _params, ctx, { from: "create" });
533
+ if (params instanceof FormData) {
534
+ opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
535
+ _params = objToFormData(_params);
536
+ }
537
+ this.axios
538
+ .post(apiUrl, _params, opt)
539
+ .then((response: ResponseData) => {
540
+ this.handleRes(
541
+ response,
542
+ (res) => {
543
+ if (this.createResMap) {
544
+ res = this.createResMap(res);
545
+ }
546
+ resolve(res);
547
+ },
548
+ reject,
549
+ );
550
+ })
551
+ .catch((err) => this.errorHandler(err, reject));
552
+ });
553
+ }
554
+
555
+ /**
556
+ * PUT 请求
557
+ * @param params 参数
558
+ * @param ctx url 替换的额外参数
559
+ * @param axiosConf axios 配置
560
+ * @returns Promise<any>
561
+ */
562
+ update(params?: RequestData | FormData, ctx?: JSONObject, axiosConf?: AxiosConfig): Promise<any> {
563
+ return new Promise(async (resolve, reject) => {
564
+ const opt: AxiosConfig = { ...this.axiosConf, ...this.updateAxiosConf, ...axiosConf };
565
+ let _params = _.cloneDeep(formDataToObj(params));
566
+ if (this.updateReqMap) {
567
+ _params = await this.updateReqMap(_params, params);
568
+ }
569
+ const apiUrl = this.getApiUrl(this.updateApi, _params, ctx, { from: "update" });
570
+ if (params instanceof FormData) {
571
+ opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
572
+ _params = objToFormData(_params);
573
+ }
574
+ this.axios
575
+ .put(apiUrl, _params, opt)
576
+ .then((response) => {
577
+ this.handleRes(
578
+ response,
579
+ (res) => {
580
+ if (this.updateResMap) {
581
+ res = this.updateResMap(res);
582
+ }
583
+ resolve(res);
584
+ },
585
+ reject,
586
+ );
587
+ })
588
+ .catch((err) => this.errorHandler(err, reject));
589
+ });
590
+ }
591
+
592
+ /**
593
+ * PATCH 请求
594
+ * @param params 参数
595
+ * @param ctx url 替换的额外参数
596
+ * @param axiosConf axios 配置
597
+ * @returns Promise<any>
598
+ */
599
+ patch(params?: RequestData | FormData, ctx?: JSONObject, axiosConf?: AxiosConfig): Promise<any> {
600
+ return new Promise(async (resolve, reject) => {
601
+ const opt: AxiosConfig = { ...this.axiosConf, ...this.patchAxiosConf, ...axiosConf };
602
+ let _params = _.cloneDeep(formDataToObj(params));
603
+ if (this.patchReqMap) {
604
+ _params = await this.patchReqMap(_params, params);
605
+ }
606
+ const apiUrl = this.getApiUrl(this.patchApi, _params, ctx, { from: "patch" });
607
+ if (params instanceof FormData) {
608
+ opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
609
+ _params = objToFormData(_params);
610
+ }
611
+ this.axios
612
+ .patch(apiUrl, _params, opt)
613
+ .then((response) => {
614
+ this.handleRes(
615
+ response,
616
+ (res) => {
617
+ if (this.patchResMap) {
618
+ res = this.patchResMap(res);
619
+ }
620
+ resolve(res);
621
+ },
622
+ reject,
623
+ );
624
+ })
625
+ .catch((err) => this.errorHandler(err, reject));
626
+ });
627
+ }
628
+
629
+ /**
630
+ * 删除接口
631
+ * @param config axios.delete config 参数
632
+ * @param config.params axios.delete url 参数
633
+ * @param config.data axios.delete data 参数
634
+ * @param ctx url 替换的额外参数
635
+ * @returns Promise<any>
636
+ */
637
+ async delete(config?: DeleteConfig, ctx?: JSONObject): Promise<any> {
638
+ let _config = _.cloneDeep(config) || {};
639
+ if (this.deleteReqMap) {
640
+ _config = await this.deleteReqMap(_config);
641
+ }
642
+ return new Promise((resolve, reject) => {
643
+ const apiUrl = this.getApiUrl(
644
+ this.deleteApi,
645
+ Object.assign(_.cloneDeep(_config), _config.params, _config.data),
646
+ ctx,
647
+ { from: "delete" },
648
+ );
649
+ this.axios
650
+ .delete(apiUrl, { ...this.axiosConf, ...this.deleteAxiosConf, ..._config })
651
+ .then((response) => {
652
+ this.handleRes(
653
+ response,
654
+ (res) => {
655
+ if (this.deleteResMap) {
656
+ res = this.deleteResMap(res);
657
+ }
658
+ resolve(res);
659
+ },
660
+ reject,
661
+ );
662
+ })
663
+ .catch((err) => this.errorHandler(err, reject));
664
+ });
665
+ }
666
+
667
+ /**
668
+ * 批量删除接口
669
+ * @param config axios.delete config 参数
670
+ * @param config.params axios.delete url 参数
671
+ * @param config.data axios.delete data 参数
672
+ * @param ctx url 替换的额外参数
673
+ * @returns Promise<any>
674
+ */
675
+ async multipleDelete(config?: DeleteConfig, ctx?: JSONObject): Promise<any> {
676
+ let _config = _.cloneDeep(config) || {};
677
+ if (this.multipleDeleteReqMap) {
678
+ _config = await this.multipleDeleteReqMap(_config);
679
+ }
680
+ return new Promise((resolve, reject) => {
681
+ const apiUrl = this.getApiUrl(
682
+ this.multipleDeleteApi,
683
+ Object.assign(_.cloneDeep(_config), _config.params, _config.data),
684
+ ctx,
685
+ { from: "multipleDelete" },
686
+ );
687
+ this.axios
688
+ .delete(apiUrl, { ...this.axiosConf, ...this.multipleDeleteAxiosConf, ..._config })
689
+ .then((response) => {
690
+ this.handleRes(
691
+ response,
692
+ (res: ResponseData) => {
693
+ if (this.multipleDeleteResMap) {
694
+ res = this.multipleDeleteResMap(res);
695
+ }
696
+ resolve(res);
697
+ },
698
+ reject,
699
+ );
700
+ })
701
+ .catch((err) => this.errorHandler(err, reject));
702
+ });
703
+ }
704
+
705
+ /**
706
+ * 处理响应结果
707
+ * @param response axios 响应对象
708
+ * @param resolve 成功回调
709
+ * @param reject 失败回调
710
+ */
711
+ handleRes(response: ResponseData, resolve: (res: any) => void, reject: (err: ApiError) => void) {
712
+ if (isCancel(response)) {
713
+ console.info("errorHandler isCancel", response);
714
+ return;
715
+ }
716
+ if (this.isResponse) {
717
+ resolve(response);
718
+ return;
719
+ }
720
+ if (this.isResponseData) {
721
+ resolve(response?.data ?? response);
722
+ return;
723
+ }
724
+ if (typeof response !== "object") {
725
+ reject(new Error("response not object") as ApiError);
726
+ return;
727
+ }
728
+
729
+ let _res: ResponseData | ResData;
730
+ _res = this.handleResponse ? this.handleResponse(response) : response;
731
+
732
+ const isAxiosResponse = (obj: any): obj is ResponseData => {
733
+ return obj && "status" in obj && "headers" in obj && "request" in obj;
734
+ };
735
+
736
+ if (isAxiosResponse(_res)) {
737
+ _res = _res.data;
738
+ }
739
+
740
+ const { code, data } = _res as ResData;
741
+ const message = this.handleMsg(response);
742
+ if (code == 200) {
743
+ const _data = data ?? {};
744
+ if (_.isObject(_data)) {
745
+ if (_data.content && _data.pageNumber && _data.total) {
746
+ _data.list = _data.content;
747
+ _data.pagination = { current: _data.pageNumber, total: _data.total };
748
+ }
749
+ // 前缀 _ 避免与 data 里已有的 message 冲突
750
+ _data._msg = message;
751
+ _data._message = message;
752
+ }
753
+ resolve(_data);
754
+ } else {
755
+ const error = new Error(message) as ApiError;
756
+ error.code = code;
757
+ error.response = response;
758
+ error._msg = message;
759
+ error._message = message;
760
+ reject(error);
761
+ }
762
+ }
763
+
764
+ /**
765
+ * 错误处理器
766
+ * @param err 错误对象
767
+ * @param reject Promise reject 回调
768
+ */
769
+ errorHandler(err: any = {}, reject: (err: ApiError) => void) {
770
+ if (isCancel(err)) {
771
+ console.info("errorHandler isCancel", err);
772
+ return;
773
+ }
774
+ if (this.isResponse) {
775
+ reject(err);
776
+ return;
777
+ }
778
+ if (this.isResponseData) {
779
+ reject(err?.data ?? err);
780
+ return;
781
+ }
782
+ const response = err?.response || err;
783
+ if (response) {
784
+ const message = this.handleMsg(response, { useStatusText: true });
785
+ const error = new Error(message) as ApiError;
786
+ error.code = response.status;
787
+ error.response = response;
788
+ if (message) {
789
+ // 前缀 _ 避免与 data 里已有的 message 冲突
790
+ error._message = message;
791
+ error._msg = message;
792
+ }
793
+ return reject(error);
794
+ }
795
+ return reject(err ?? { _msg: _$Temp.networkErrMsg });
796
+ }
797
+
798
+ /**
799
+ * 处理错误消息
800
+ * @param response 响应对象
801
+ * @param opt 选项
802
+ * @returns 错误消息
803
+ */
804
+ handleMsg(
805
+ response: any,
806
+ opt: HandleMsgOptions = {
807
+ // 是否使用 response.statusText 作为兜底 msg
808
+ useStatusText: false,
809
+ },
810
+ ): string {
811
+ const { useStatusText } = opt || {};
812
+ let message =
813
+ (response.data && (response.data.message || response.data.msg)) ||
814
+ response.msg ||
815
+ response.message ||
816
+ this.getNetworkErrMsg(response);
817
+
818
+ if (!message && useStatusText) {
819
+ message = response.statusText;
820
+ }
821
+
822
+ return message || _$Temp.defaultErrMsg;
823
+ }
824
+
825
+ /**
826
+ * 获取网络错误消息
827
+ * @param httpCode HTTP 状态码
828
+ * @returns 错误消息
829
+ */
830
+ getNetworkErrMsg(httpCode: string): string {
831
+ const { networkErrMsg } = _$Temp;
832
+ if (httpCode === "ERR_NETWORK") {
833
+ return networkErrMsg;
834
+ }
835
+ return checkNetwork() ? "" : networkErrMsg;
836
+ }
837
+ }
838
+
839
+ export {
840
+ axios,
841
+ checkNetwork,
842
+ DataModel,
843
+ formDataToObj,
844
+ objToFormData,
845
+ setDefaultAxios,
846
+ setDefaultErrMsg,
847
+ setNetworkErrMsg,
848
+ };
849
+
850
+ export default DataModel;