@hzab/data-model 1.4.1 → 1.6.0-beta

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/CHANGELOG.md CHANGED
@@ -1,3 +1,12 @@
1
+ # @hzab/data-model@1.6.0
2
+
3
+ fix: 注释;通用函数抽离
4
+ feat: ArrayDataModel 本地数据 DataModel
5
+
6
+ # @hzab/data-model@1.5.0
7
+
8
+ - feat: 增加 patch 请求方式函数
9
+
1
10
  # @hzab/data-model@1.4.1
2
11
 
3
12
  - fix: handleMsg useStatusText 问题修复
package/README.md CHANGED
@@ -39,10 +39,14 @@ const listDM = new DataModel({
39
39
  getListMap,
40
40
  // 列表请求函数
41
41
  getListFunc,
42
- // 编辑接口 put url
42
+ // put 编辑接口 url
43
43
  updateApi,
44
- // 编辑接口 put 入参枚举函数
44
+ // put 编辑接口 入参枚举函数
45
45
  updateMap,
46
+ // patch 编辑接口 url
47
+ patchApi,
48
+ // patch 编辑接口 入参枚举函数
49
+ patchMap,
46
50
  // 删除接口 delete url
47
51
  deleteApi,
48
52
  // 批量删除接口 delete url
@@ -61,6 +65,8 @@ const listDM = new DataModel({
61
65
  createAxiosConf,
62
66
  // update 接口 axios 相关配置
63
67
  updateAxiosConf,
68
+ // patch 接口 axios 相关配置
69
+ patchAxiosConf,
64
70
  // delete 接口 axios 相关配置
65
71
  deleteAxiosConf,
66
72
  // multipleDelete 接口 axios 相关配置
@@ -81,6 +87,10 @@ const listDM = new DataModel({
81
87
  updateReqMap,
82
88
  // 编辑接口 put 出参枚举函数
83
89
  updateResMap,
90
+ // patch 编辑接口 put 入参枚举函数
91
+ patchReqMap,
92
+ // patch 编辑接口 put 出参枚举函数
93
+ patchResMap,
84
94
  // 删除接口 delete 入参枚举函数
85
95
  deleteReqMap,
86
96
  // 删除接口 delete 出参枚举函数
@@ -126,6 +136,7 @@ function Demo({ orgId }) {
126
136
  | getApi | string | 否 | - | 详情 get 接口地址 |
127
137
  | getListApi | string | 否 | - | 列表 get 接口地址 |
128
138
  | updateApi | string | 否 | - | put 接口地址 |
139
+ | patchApi | string | 否 | - | patch 接口地址 |
129
140
  | deleteApi | string | 否 | - | delete 接口地址 |
130
141
  | multipleDeleteApi | string | 否 | - | 批量删除 delete 接口地址 |
131
142
  | createMap | Function | 否 | - | createApi 接口提交前的处理函数 |
@@ -133,12 +144,14 @@ function Demo({ orgId }) {
133
144
  | getListMap | Function | 否 | - | getListApi 接口返回结果的处理函数 |
134
145
  | getListFunc | Function | 否 | - | 自定义的列表请求函数,优先级高于 getListApi |
135
146
  | updateMap | Function | 否 | - | updateApi 接口提交前的处理函数 |
147
+ | patchMap | Function | 否 | - | patchApi 接口提交前的处理函数 |
136
148
  | axios | Object | 否 | - | axios 实例对象 |
137
149
  | axiosConf | Object | 否 | - | axios 相关配置 |
138
150
  | getListAxiosConf | Object | 否 | - | getList 接口 axios 相关配置 |
139
151
  | getAxiosConf | Object | 否 | - | get 接口 axios 相关配置 |
140
152
  | createAxiosConf | Object | 否 | - | create 接口 axios 相关配置 |
141
153
  | updateAxiosConf | Object | 否 | - | update 接口 axios 相关配置 |
154
+ | patchAxiosConf | Object | 否 | - | patch 接口 axios 相关配置 |
142
155
  | deleteAxiosConf | Object | 否 | - | delete 接口 axios 相关配置 |
143
156
  | multipleDeleteAxiosConf | Object | 否 | - | multipleDelete 接口 axios 相关配置 |
144
157
  | getListReqMap | Function | 否 | - | 列表接口 get 入参枚举函数 |
@@ -149,6 +162,8 @@ function Demo({ orgId }) {
149
162
  | createResMap | Function | 否 | - | 新增接口 get 出参枚举函数 |
150
163
  | updateReqMap | Function | 否 | - | 编辑接口 get 入参枚举函数 |
151
164
  | updateResMap | Function | 否 | - | 编辑接口 get 出参枚举函数 |
165
+ | patchReqMap | Function | 否 | - | patch 接口 get 入参枚举函数 |
166
+ | patchResMap | Function | 否 | - | patch 接口 get 出参枚举函数 |
152
167
  | deleteReqMap | Function | 否 | - | 删除接口 get 入参枚举函数 |
153
168
  | deleteResMap | Function | 否 | - | 删除接口 get 出参枚举函数 |
154
169
  | multipleDeleteReqMap | Function | 否 | - | 批量删除接口 get 入参枚举函数 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hzab/data-model",
3
- "version": "1.4.1",
3
+ "version": "1.6.0-beta",
4
4
  "description": "data model",
5
5
  "main": "src",
6
6
  "scripts": {
@@ -21,12 +21,14 @@
21
21
  "author": "CaiYansong",
22
22
  "license": "ISC",
23
23
  "devDependencies": {
24
- "@hzab/permissions": "0.0.4",
25
- "@hzab/webpack-config": "^0.0.15",
24
+ "@hzab/permissions": "^0.1.1",
25
+ "@hzab/webpack-config": "^0.7.1",
26
26
  "@types/react": "^17.0.62",
27
27
  "@types/react-dom": "^17.0.20",
28
28
  "antd": "^4.14.0",
29
+ "axios": "^1.6.2",
29
30
  "eslint": "^8.30.0",
31
+ "js-cookie": "^3.0.5",
30
32
  "less": "^4.1.3",
31
33
  "mobx": "^6.7.0",
32
34
  "mobx-react": "^7.6.0",
@@ -34,17 +36,16 @@
34
36
  "react-dom": "^17.0.2",
35
37
  "react-router-dom": "^6.14.1",
36
38
  "typedoc": "^0.24.8",
37
- "typescript": "^4.9.4",
38
- "axios": "^1.6.2",
39
- "js-cookie": "^3.0.5"
39
+ "typescript": "^4.9.4"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "axios": ">=1.6.2",
43
43
  "js-cookie": ">=3.0.5"
44
44
  },
45
45
  "dependencies": {
46
- "axios": "^1.6.2",
47
- "js-cookie": "^3.0.5"
46
+ "axios": ">=1.6.2",
47
+ "js-cookie": ">=3.0.5",
48
+ "nanoid": "^3.3.7"
48
49
  },
49
50
  "directories": {
50
51
  "lib": "lib"
@@ -0,0 +1,195 @@
1
+ import { nanoid } from "nanoid";
2
+ import _ from "lodash";
3
+
4
+ export const STATE_CODE = {
5
+ SUC: 200,
6
+ NOT_FOUNT: 404,
7
+ ERR: 500,
8
+ ERR_INPUT_ID: 501,
9
+ };
10
+
11
+ /**
12
+ * 数组模拟数据库存储
13
+ * TODO: FormData? 考虑到文件存储问题
14
+ */
15
+ export class ArrayUtils {
16
+ _idKey = "id";
17
+ _list = [];
18
+ constructor(params) {
19
+ const { idKey = "id", list } = params;
20
+ /** 子项唯一标志字段 */
21
+ this._idKey = idKey || "id";
22
+ /** 列表数据 */
23
+ this._list = list || [];
24
+ }
25
+
26
+ /**
27
+ * 通过 id 获取子项
28
+ * @param {*} id
29
+ * @returns
30
+ */
31
+ findItemById(id) {
32
+ if (hasId(id)) {
33
+ return null;
34
+ }
35
+ const { _idKey } = this;
36
+ return _.cloneDeep(this._list.find((it) => it[_idKey] === id));
37
+ }
38
+
39
+ /**
40
+ * 通过 id 获取子项
41
+ * @param {*} id
42
+ * @returns
43
+ */
44
+ findItem(query = {}) {
45
+ const { _idKey } = this;
46
+ const id = query[_idKey];
47
+ if (hasId(id)) {
48
+ return this.findItemById(id);
49
+ }
50
+ // TODO: query 查询
51
+ return _.cloneDeep(this._list.find((it) => it[_idKey] === id));
52
+ }
53
+
54
+ /**
55
+ * 获取列表
56
+ * TODO: 搜索?
57
+ * @param {*} query
58
+ */
59
+ findListByQuery(query) {
60
+ const { pageNum = 1, pageSize = 10 } = query || {};
61
+ const { _list } = this;
62
+ // 边界检查
63
+ if (pageNum < 1 || pageSize <= 0) {
64
+ return { list: [], pagination: { current: 1, total: 0 } };
65
+ }
66
+ // 计算起始索引
67
+ const startIndex = (pageNum - 1) * pageSize;
68
+ // 如果起始索引超出数组长度,返回空数组
69
+ if (startIndex >= _list.length) {
70
+ return { list: [], pagination: { current: 1, total: 0 } };
71
+ }
72
+ // 计算结束索引
73
+ const endIndex = startIndex + pageSize;
74
+
75
+ // 使用 slice 方法截取数据
76
+ return { list: _list.slice(startIndex, endIndex), pagination: { current: pageNum, total: this.getCount() } };
77
+ }
78
+
79
+ /**
80
+ * 获取完整列表
81
+ */
82
+ findAllList() {
83
+ return _.cloneDeep(this._list);
84
+ }
85
+
86
+ /**
87
+ * 获取总数
88
+ * @returns
89
+ */
90
+ getCount() {
91
+ return this._list.length;
92
+ }
93
+
94
+ /**
95
+ * push 数据
96
+ * @param {*} data
97
+ */
98
+ pushItem(data) {
99
+ // TODO: id 去重
100
+ const item = _.cloneDeep(data);
101
+ this.setId(item);
102
+ this._list.push(item);
103
+ return STATE_CODE.SUC;
104
+ }
105
+
106
+ /**
107
+ * unshift 数据
108
+ * @param {*} data
109
+ */
110
+ unshiftItem(data) {
111
+ // TODO: id 去重
112
+ const item = _.cloneDeep(data);
113
+ this.setId(item);
114
+ this._list.unshift(item);
115
+ return STATE_CODE.SUC;
116
+ }
117
+
118
+ /**
119
+ * 根据 id 更新子项——直接替换
120
+ * @param {Object} data
121
+ * @returns
122
+ */
123
+ replaceItem(data) {
124
+ const { _idKey, _list } = this;
125
+ const id = data[_idKey];
126
+ if (hasId(id)) {
127
+ return STATE_CODE.ERR_INPUT_ID;
128
+ }
129
+ const idx = _list.findIndex((it) => it[_idKey] === id);
130
+ if (idx < 0) {
131
+ return STATE_CODE.NOT_FOUNT;
132
+ }
133
+ _list.splice(idx, 1, data);
134
+ return STATE_CODE.SUC;
135
+ }
136
+
137
+ /**
138
+ * 根据 id 更新子项——仅修改传入的数据
139
+ * @param {Object} data
140
+ * @returns
141
+ */
142
+ updateItemValue(data) {
143
+ const { _idKey, _list } = this;
144
+ const id = data[_idKey];
145
+ if (hasId(id)) {
146
+ return STATE_CODE.ERR_INPUT_ID;
147
+ }
148
+ const item = _list.find((it) => it[_idKey] === id);
149
+ if (!item) {
150
+ return STATE_CODE.NOT_FOUNT;
151
+ }
152
+ Object.keys(data).forEach((key) => {
153
+ item[key] = data[key];
154
+ });
155
+ return STATE_CODE.SUC;
156
+ }
157
+
158
+ /**
159
+ * 删除子项
160
+ * @param {*} id
161
+ * @param {*} data
162
+ * @returns
163
+ */
164
+ delItem(id) {
165
+ const { _idKey, _list } = this;
166
+ if (hasId(id)) {
167
+ return STATE_CODE.ERR_INPUT_ID;
168
+ }
169
+ const idx = _list.findIndex((it) => it[_idKey] === id);
170
+ if (idx < 0) {
171
+ return STATE_CODE.NOT_FOUNT;
172
+ }
173
+ _list.splice(idx, 1);
174
+ return STATE_CODE.SUC;
175
+ }
176
+
177
+ /**
178
+ * 子项没有 id 的时候自动添加
179
+ * @param {*} item
180
+ * @returns
181
+ */
182
+ setId(item) {
183
+ const { _idKey } = this;
184
+ if (!item[_idKey]) {
185
+ item[_idKey] = nanoid();
186
+ }
187
+ return item;
188
+ }
189
+ }
190
+
191
+ export const hasId = (id) => {
192
+ return _.isNil(id) || id === "";
193
+ };
194
+
195
+ export default ArrayUtils;
@@ -0,0 +1,392 @@
1
+ import _ from "lodash";
2
+
3
+ import { objToFormData, formDataToObj, _$Temp } from "./utils";
4
+ import ArrayUtils, { STATE_CODE } from "./ArrayUtils";
5
+
6
+ /**
7
+ * ArrayDataModel 本地数据 DataModel
8
+ */
9
+ class ArrayDataModel extends ArrayUtils {
10
+ constructor(params) {
11
+ super(params);
12
+ const {
13
+ ctx,
14
+ query,
15
+ createApi,
16
+ createMap,
17
+ getApi,
18
+ getMap,
19
+ getListApi,
20
+ getListMap,
21
+ getListFunc,
22
+ updateApi,
23
+ updateMap,
24
+ patchApi,
25
+ patchMap,
26
+ deleteApi,
27
+ multipleDeleteApi,
28
+ } = params;
29
+
30
+ /** 请求 url 替换的额外参数 */
31
+ this.ctx = ctx || {};
32
+ /** GET 请求的参数 */
33
+ this.query = query || {};
34
+
35
+ /** POST 接口地址 */
36
+ this.createApi = createApi;
37
+ /** POST 接口提交前的数据处理回调 record => (record) */
38
+ this.createMap = createMap;
39
+ /** GET 详情 接口地址 */
40
+ this.getApi = getApi;
41
+ /** GET 详情 接口返回后的数据处理回调 record => (record) */
42
+ this.getMap = getMap;
43
+ /** GET 列表 接口地址 */
44
+ this.getListApi = getListApi;
45
+ /** GET 列表 接口返回后的数据处理回调 record => (record) */
46
+ this.getListMap = getListMap;
47
+ /** GET 列表 接口回调,用于自定义列表请求接口。query => ({list: [], pagination: { total: 0 }}) 优先级高于 getListApi */
48
+ this.getListFunc = getListFunc;
49
+ /** PUT 接口地址 */
50
+ this.updateApi = updateApi;
51
+ /** PUT 接口提交前的数据处理回调 record => (record) */
52
+ this.updateMap = updateMap;
53
+ /** PATCH 接口地址 */
54
+ this.patchApi = patchApi;
55
+ /** PATCH 接口提交前的数据处理回调 record => (record) */
56
+ this.patchMap = patchMap;
57
+ /** DELETE 接口地址 */
58
+ this.deleteApi = deleteApi;
59
+ /** DELETE 批量删除 接口地址 */
60
+ this.multipleDeleteApi = multipleDeleteApi;
61
+
62
+ const {
63
+ getListReqMap,
64
+ getListResMap,
65
+ getReqMap,
66
+ getResMap,
67
+ createReqMap,
68
+ createResMap,
69
+ updateReqMap,
70
+ updateResMap,
71
+ patchReqMap,
72
+ patchResMap,
73
+ deleteReqMap,
74
+ deleteResMap,
75
+ multipleDeleteReqMap,
76
+ multipleDeleteResMap,
77
+ } = params || {};
78
+
79
+ /** GET 列表 接口请求前数据处理回调 */
80
+ this.getListReqMap = getListReqMap;
81
+ /** GET 列表 接口请求结果数据处理回调 */
82
+ this.getListResMap = getListResMap;
83
+ /** GET 详情 接口请求前数据处理回调 */
84
+ this.getReqMap = getReqMap;
85
+ /** GET 详情 接口请求结果数据处理回调 */
86
+ this.getResMap = getResMap;
87
+ /** POST 接口请求前数据处理回调 */
88
+ this.createReqMap = createReqMap;
89
+ /** POST 接口请求结果数据处理回调 */
90
+ this.createResMap = createResMap;
91
+ /** PUT 接口请求前数据处理回调 */
92
+ this.updateReqMap = updateReqMap;
93
+ /** PUT 接口请求结果数据处理回调 */
94
+ this.updateResMap = updateResMap;
95
+ /** PATCH 接口请求前数据处理回调 */
96
+ this.patchReqMap = patchReqMap;
97
+ /** PATCH 接口请求结果数据处理回调 */
98
+ this.patchResMap = patchResMap;
99
+ /** DELETE 接口请求前数据处理回调 */
100
+ this.deleteReqMap = deleteReqMap;
101
+ /** DELETE 接口请求结果数据处理回调 */
102
+ this.deleteResMap = deleteResMap;
103
+ /** DELETE 批量删除 接口请求前数据处理回调 */
104
+ this.multipleDeleteReqMap = multipleDeleteReqMap;
105
+ /** DELETE 批量删除 接口请求结果数据处理回调 */
106
+ this.multipleDeleteResMap = multipleDeleteResMap;
107
+ }
108
+
109
+ /**
110
+ * GET 详情请求
111
+ * @param {Object} q query 参数
112
+ * @returns
113
+ */
114
+ get(q = {}) {
115
+ let query = _.merge({}, this.query, q);
116
+ query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
117
+
118
+ if (this.getReqMap) {
119
+ query = this.getReqMap(query);
120
+ }
121
+
122
+ return new Promise((resolve, reject) => {
123
+ resolve(this.getResMap(this.findItem(query)));
124
+ });
125
+ }
126
+
127
+ /**
128
+ * GET 列表请求
129
+ * @param {Object} q query 参数
130
+ * @returns
131
+ */
132
+ async getList(q) {
133
+ let query = _.merge({}, this.query, q);
134
+ query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
135
+
136
+ if (this.getListReqMap) {
137
+ query = this.getListReqMap(query);
138
+ }
139
+
140
+ let resultList = null;
141
+ if (this.getListFunc) {
142
+ resultList = await this.getListFunc(query);
143
+ if (this.getListResMap) {
144
+ resultList = this.getListResMap(resultList);
145
+ }
146
+ } else {
147
+ const getPro = this.findListByQuery(query);
148
+ resultList = await getPro;
149
+ if (this.getListResMap) {
150
+ resultList = this.getListResMap(resultList);
151
+ }
152
+ }
153
+ return resultList;
154
+ }
155
+
156
+ /**
157
+ * POST 请求
158
+ * @param {Object} params 参数
159
+ * @returns
160
+ */
161
+ create(params) {
162
+ return new Promise((resolve, reject) => {
163
+ const _params = this.handleInputParams(params, this.createReqMap);
164
+ const res = this.pushItem(_params);
165
+ if (res === STATE_CODE.SUC) {
166
+ let _res = {};
167
+ if (this.createResMap) {
168
+ _res = this.createResMap();
169
+ }
170
+ resolve(_res);
171
+ } else {
172
+ reject(res);
173
+ }
174
+ });
175
+ }
176
+
177
+ /**
178
+ * PUT 请求
179
+ * @param {Object} params 参数
180
+ * @returns
181
+ */
182
+ update(params) {
183
+ return new Promise((resolve, reject) => {
184
+ const _params = this.handleInputParams(params, this.updateReqMap);
185
+ const res = this.replaceItem(_params);
186
+ if (res === STATE_CODE.SUC) {
187
+ let _res = {};
188
+ if (this.updateResMap) {
189
+ _res = this.updateResMap();
190
+ }
191
+ resolve(_res);
192
+ } else {
193
+ reject(res);
194
+ }
195
+ });
196
+ }
197
+
198
+ /**
199
+ * PATCH 请求
200
+ * @param {Object} params 参数
201
+ * @returns
202
+ */
203
+ patch(params) {
204
+ return new Promise((resolve, reject) => {
205
+ const _params = this.handleInputParams(params, this.patchReqMap);
206
+ const res = this.updateItemValue(_params);
207
+ if (res === STATE_CODE.SUC) {
208
+ let _res = {};
209
+ if (this.patchResMap) {
210
+ _res = this.patchResMap();
211
+ }
212
+ resolve(_res);
213
+ } else {
214
+ reject(res);
215
+ }
216
+ });
217
+ }
218
+
219
+ /**
220
+ * 删除接口
221
+ * @param {*} config axios.delete config 参数,
222
+ * @param {*} config.params axios.delete url 参数,
223
+ * @param {*} config.data axios.delete data 参数,
224
+ * @param {*} ctx
225
+ * @returns
226
+ */
227
+ delete(config, ctx) {
228
+ let _config = _.cloneDeep(config) || {};
229
+ if (this.deleteReqMap) {
230
+ _config = this.deleteReqMap(_config);
231
+ }
232
+ return new Promise((resolve, reject) => {
233
+ const { _idKey } = this;
234
+ const id = config[_idKey] || config.params?.[_idKey] || config.data?.[_idKey] || ctx[_idKey];
235
+ const res = this.delItem(id);
236
+ console.log("res", res);
237
+
238
+ if (res === STATE_CODE.SUC) {
239
+ let _res = {};
240
+ if (this.deleteResMap) {
241
+ _res = this.deleteResMap();
242
+ }
243
+ resolve(_res);
244
+ } else {
245
+ reject(res);
246
+ }
247
+ });
248
+ }
249
+
250
+ /**
251
+ * 批量删除接口
252
+ * @param {*} config axios.delete config 参数,
253
+ * @param {*} config.params axios.delete url 参数,
254
+ * @param {*} config.data axios.delete data 参数,
255
+ * @param {*} ctx
256
+ * @returns
257
+ */
258
+ multipleDelete(config, ctx) {
259
+ let _config = _.cloneDeep(config) || {};
260
+ if (this.multipleDeleteReqMap) {
261
+ _config = this.multipleDeleteReqMap(_config);
262
+ }
263
+ return new Promise((resolve, reject) => {
264
+ const { _idKey } = this;
265
+ let ids = config[_idKey] || config.params?.[_idKey] || config.data?.[_idKey] || ctx[_idKey];
266
+
267
+ if (typeof ids === "string") {
268
+ ids = ids.split(",");
269
+ }
270
+
271
+ if (Array.isArray(ids)) {
272
+ const sucList = [];
273
+ const failList = [];
274
+ ids.forEach((id) => {
275
+ try {
276
+ const res = this.delItem(id);
277
+ if (res === STATE_CODE.SUC) {
278
+ sucList.push(id);
279
+ } else {
280
+ failList.push(id);
281
+ }
282
+ } catch (error) {
283
+ console.log("error", error);
284
+ }
285
+ });
286
+ if (sucList.length > 0) {
287
+ let _res = { sucList, failList };
288
+ if (this.multipleDeleteResMap) {
289
+ _res = this.multipleDeleteResMap();
290
+ }
291
+ resolve(_res);
292
+ } else {
293
+ reject({ failList });
294
+ }
295
+ return;
296
+ }
297
+
298
+ reject({});
299
+ });
300
+ }
301
+
302
+ /**
303
+ * 处理传入的数据
304
+ * @returns
305
+ */
306
+ handleInputParams(params, reqMapFn) {
307
+ let _params = _.cloneDeep(formDataToObj(params));
308
+ if (reqMapFn) {
309
+ _params = reqMapFn.bind(this)(_params, params);
310
+ }
311
+ // TODO: FormData 文件存储?
312
+ // if (params instanceof FormData) {
313
+ // _params = objToFormData(_params);
314
+ // }
315
+ return _params;
316
+ }
317
+
318
+ handleRes(response, resolve, reject) {
319
+ if (typeof response !== "object") {
320
+ reject(new Error("response not object"));
321
+ return;
322
+ }
323
+ let _res = response;
324
+ // 兼容 传入的是 response.data 的情况
325
+ if (_res.data && _res.headers && _res.request) {
326
+ _res = _res.data;
327
+ }
328
+ const { code, data } = _res;
329
+ const message = this.handleMsg(response);
330
+ if (code == 200) {
331
+ let _data = data ?? {};
332
+ if (_.isObject(_data)) {
333
+ if (_data.content && _data.pageNumber && _data.total) {
334
+ _data.list = _data.content;
335
+ _data.pagination = { current: _data.pageNumber, total: _data.total };
336
+ }
337
+ // 前缀 _ 避免与 data 里已有的 message 冲突
338
+ _data._msg = message;
339
+ _data._message = message;
340
+ }
341
+ resolve(_data);
342
+ } else {
343
+ const error = new Error(message);
344
+ error.code = code;
345
+ error.response = response;
346
+ error._msg = message;
347
+ error._message = message;
348
+ reject(error);
349
+ }
350
+ }
351
+
352
+ errorHandler(err, reject) {
353
+ const response = err.response || err;
354
+ if (response) {
355
+ const message = this.handleMsg(response, { useStatusText: true });
356
+ const error = new Error(message);
357
+ error.code = response.status;
358
+ error.response = response;
359
+ if (message) {
360
+ // 前缀 _ 避免与 data 里已有的 message 冲突
361
+ error._message = message;
362
+ error._msg = message;
363
+ }
364
+ return reject(error);
365
+ }
366
+ return reject(err || { _msg: _$Temp.defaultErrMsg });
367
+ }
368
+
369
+ handleMsg(
370
+ response,
371
+ opt = {
372
+ // 是否使用 response.statusText 作为兜底 msg
373
+ useStatusText: false,
374
+ },
375
+ ) {
376
+ const {
377
+ // 是否使用 response.statusText 作为兜底 msg
378
+ useStatusText,
379
+ } = opt || {};
380
+ let message = (response.data && (response.data.message || response.data.msg)) || response.msg;
381
+
382
+ if (!message && useStatusText) {
383
+ message = response.statusText;
384
+ }
385
+
386
+ return message || _$Temp.defaultErrMsg;
387
+ }
388
+ }
389
+
390
+ export { ArrayDataModel };
391
+
392
+ export default ArrayDataModel;
package/src/data-model.js CHANGED
@@ -1,13 +1,7 @@
1
1
  import _ from "lodash";
2
2
  import axios from "axios";
3
3
 
4
- const DEFAULT_MSG = "未知错误";
5
- const NETWORK_MSG = "网络异常,请检查网络是否开启";
6
-
7
- const _$Temp = {
8
- defaultErrMsg: DEFAULT_MSG,
9
- networkErrMsg: NETWORK_MSG,
10
- };
4
+ import { objToFormData, formDataToObj, _$Temp, setDefaultAxios, setDefaultErrMsg, setNetworkErrMsg } from "./utils";
11
5
 
12
6
  class DataModel {
13
7
  constructor(params) {
@@ -20,40 +14,57 @@ class DataModel {
20
14
  getMap,
21
15
  getListApi,
22
16
  getListMap,
23
- // 统一 response 回调,用于处理定制 response 格式
24
17
  handleResponse,
25
18
  getListFunc,
26
19
  updateApi,
27
20
  updateMap,
21
+ patchApi,
22
+ patchMap,
28
23
  deleteApi,
29
24
  multipleDeleteApi,
30
- axios: as,
31
- axiosConf,
32
25
  // 是否返回完整的接口数据(response.data)
33
26
  isResponseData,
34
27
  // 是否直接返回 response
35
28
  isResponse,
36
29
  } = params;
37
30
 
31
+ /** 是否返回完整的接口数据(response.data) */
38
32
  this.isResponseData = isResponseData;
33
+ /** 是否直接返回 response */
39
34
  this.isResponse = isResponse;
35
+ /** 统一 response 回调,用于处理定制 response 格式 */
36
+ this.handleResponse = handleResponse;
40
37
 
38
+ /** 请求 url 替换的额外参数 */
41
39
  this.ctx = ctx || {};
40
+ /** GET 请求的参数 */
42
41
  this.query = query || {};
43
- this.axios = as || _$Temp.axios || axios;
44
- this.axiosConf = axiosConf || {};
45
42
 
43
+ /** POST 接口地址 */
46
44
  this.createApi = createApi;
45
+ /** POST 接口提交前的数据处理回调 record => (record) */
47
46
  this.createMap = createMap;
47
+ /** GET 详情 接口地址 */
48
48
  this.getApi = getApi;
49
+ /** GET 详情 接口返回后的数据处理回调 record => (record) */
49
50
  this.getMap = getMap;
51
+ /** GET 列表 接口地址 */
50
52
  this.getListApi = getListApi;
53
+ /** GET 列表 接口返回后的数据处理回调 record => (record) */
51
54
  this.getListMap = getListMap;
52
- this.handleResponse = handleResponse;
55
+ /** GET 列表 接口回调,用于自定义列表请求接口。query => ({list: [], pagination: { total: 0 }}) 优先级高于 getListApi */
53
56
  this.getListFunc = getListFunc;
57
+ /** PUT 接口地址 */
54
58
  this.updateApi = updateApi;
59
+ /** PUT 接口提交前的数据处理回调 record => (record) */
55
60
  this.updateMap = updateMap;
61
+ /** PATCH 接口地址 */
62
+ this.patchApi = patchApi;
63
+ /** PATCH 接口提交前的数据处理回调 record => (record) */
64
+ this.patchMap = patchMap;
65
+ /** DELETE 接口地址 */
56
66
  this.deleteApi = deleteApi;
67
+ /** DELETE 批量删除 接口地址 */
57
68
  this.multipleDeleteApi = multipleDeleteApi;
58
69
 
59
70
  const {
@@ -65,40 +76,85 @@ class DataModel {
65
76
  createResMap,
66
77
  updateReqMap,
67
78
  updateResMap,
79
+ patchReqMap,
80
+ patchResMap,
68
81
  deleteReqMap,
69
82
  deleteResMap,
70
83
  multipleDeleteReqMap,
71
84
  multipleDeleteResMap,
72
85
  } = params || {};
86
+
87
+ /** GET 列表 接口请求前数据处理回调 */
73
88
  this.getListReqMap = getListReqMap;
89
+ /** GET 列表 接口请求结果数据处理回调 */
74
90
  this.getListResMap = getListResMap;
91
+ /** GET 详情 接口请求前数据处理回调 */
75
92
  this.getReqMap = getReqMap;
93
+ /** GET 详情 接口请求结果数据处理回调 */
76
94
  this.getResMap = getResMap;
95
+ /** POST 接口请求前数据处理回调 */
77
96
  this.createReqMap = createReqMap;
97
+ /** POST 接口请求结果数据处理回调 */
78
98
  this.createResMap = createResMap;
99
+ /** PUT 接口请求前数据处理回调 */
79
100
  this.updateReqMap = updateReqMap;
101
+ /** PUT 接口请求结果数据处理回调 */
80
102
  this.updateResMap = updateResMap;
103
+ /** PATCH 接口请求前数据处理回调 */
104
+ this.patchReqMap = patchReqMap;
105
+ /** PATCH 接口请求结果数据处理回调 */
106
+ this.patchResMap = patchResMap;
107
+ /** DELETE 接口请求前数据处理回调 */
81
108
  this.deleteReqMap = deleteReqMap;
109
+ /** DELETE 接口请求结果数据处理回调 */
82
110
  this.deleteResMap = deleteResMap;
111
+ /** DELETE 批量删除 接口请求前数据处理回调 */
83
112
  this.multipleDeleteReqMap = multipleDeleteReqMap;
113
+ /** DELETE 批量删除 接口请求结果数据处理回调 */
84
114
  this.multipleDeleteResMap = multipleDeleteResMap;
85
115
 
116
+ // axios 相关配置
86
117
  const {
118
+ axios: as,
119
+ axiosConf,
87
120
  getListAxiosConf,
88
121
  getAxiosConf,
89
122
  createAxiosConf,
90
123
  updateAxiosConf,
124
+ patchAxiosConf,
91
125
  deleteAxiosConf,
92
126
  multipleDeleteAxiosConf,
93
127
  } = params || {};
128
+
129
+ /** 请求的 axios 实例 */
130
+ this.axios = as || _$Temp.axios || axios;
131
+ /** axios 配置 */
132
+ this.axiosConf = axiosConf || {};
133
+
134
+ /** GET 列表接口 axios 配置 */
94
135
  this.getListAxiosConf = getListAxiosConf;
136
+ /** GET 详情接口 axios 配置 */
95
137
  this.getAxiosConf = getAxiosConf;
138
+ /** POST 接口 axios 配置 */
96
139
  this.createAxiosConf = createAxiosConf;
140
+ /** PUT 接口 axios 配置 */
97
141
  this.updateAxiosConf = updateAxiosConf;
142
+ /** PATCH 接口 axios 配置 */
143
+ this.patchAxiosConf = patchAxiosConf;
144
+ /** DELETE 接口 axios 配置 */
98
145
  this.deleteAxiosConf = deleteAxiosConf;
146
+ /** DELETE 批量删除接口 axios 配置 */
99
147
  this.multipleDeleteAxiosConf = multipleDeleteAxiosConf;
100
148
  }
101
149
 
150
+ /**
151
+ * 获取请求 url 地址
152
+ * @param {string} api 接口地址 https://a.com/test/:oId/:uId
153
+ * @param {Object} record { uId: 81 }
154
+ * @param {Object} ctx { oId: 100 }
155
+ * @param {Object} opt
156
+ * @returns
157
+ */
102
158
  getApiUrl(api, record, ctx = this.ctx, opt) {
103
159
  const { from } = opt ?? {};
104
160
  if (!api) {
@@ -116,6 +172,13 @@ class DataModel {
116
172
  return apiUrl;
117
173
  }
118
174
 
175
+ /**
176
+ * GET 详情请求
177
+ * @param {Object} q query 参数
178
+ * @param {Object} ctx url 替换的额外参数
179
+ * @param {Object} axiosConf axios 配置
180
+ * @returns
181
+ */
119
182
  get(q = {}, ctx = {}, axiosConf) {
120
183
  let query = _.merge({}, this.query, q);
121
184
  query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
@@ -152,6 +215,13 @@ class DataModel {
152
215
  });
153
216
  }
154
217
 
218
+ /**
219
+ * GET 列表请求
220
+ * @param {Object} q query 参数
221
+ * @param {Object} ctx url 替换的额外参数
222
+ * @param {Object} axiosConf axios 配置
223
+ * @returns
224
+ */
155
225
  async getList(q, ctx, axiosConf) {
156
226
  let query = _.merge({}, this.query, q);
157
227
  query = _.pickBy(query, (val) => !_.isNil(val) && val !== "");
@@ -163,6 +233,9 @@ class DataModel {
163
233
  let resultList = null;
164
234
  if (this.getListFunc) {
165
235
  resultList = await this.getListFunc(query);
236
+ if (this.getListResMap) {
237
+ resultList = this.getListResMap(resultList);
238
+ }
166
239
  } else {
167
240
  const getPro = new Promise((resolve, reject) => {
168
241
  const apiUrl = this.getApiUrl(this.getListApi, q, ctx, { from: "getList" });
@@ -196,6 +269,13 @@ class DataModel {
196
269
  return resultList;
197
270
  }
198
271
 
272
+ /**
273
+ * POST 请求
274
+ * @param {Object} params 参数
275
+ * @param {Object} ctx url 替换的额外参数
276
+ * @param {Object} axiosConf axios 配置
277
+ * @returns
278
+ */
199
279
  create(params, ctx, axiosConf) {
200
280
  return new Promise((resolve, reject) => {
201
281
  const opt = {
@@ -230,6 +310,13 @@ class DataModel {
230
310
  });
231
311
  }
232
312
 
313
+ /**
314
+ * PUT 请求
315
+ * @param {Object} params 参数
316
+ * @param {Object} ctx url 替换的额外参数
317
+ * @param {Object} axiosConf axios 配置
318
+ * @returns
319
+ */
233
320
  update(params, ctx, axiosConf) {
234
321
  return new Promise((resolve, reject) => {
235
322
  const opt = { ...this.axiosConf, ...this.updateAxiosConf, ...axiosConf };
@@ -260,6 +347,43 @@ class DataModel {
260
347
  });
261
348
  }
262
349
 
350
+ /**
351
+ * PATCH 请求
352
+ * @param {Object} params 参数
353
+ * @param {Object} ctx url 替换的额外参数
354
+ * @param {Object} axiosConf axios 配置
355
+ * @returns
356
+ */
357
+ patch(params, ctx, axiosConf) {
358
+ return new Promise((resolve, reject) => {
359
+ const opt = { ...this.axiosConf, ...this.patchAxiosConf, ...axiosConf };
360
+ let _params = _.cloneDeep(formDataToObj(params));
361
+ if (this.patchReqMap) {
362
+ _params = this.patchReqMap(_params, params);
363
+ }
364
+ const apiUrl = this.getApiUrl(this.patchApi, _params, ctx, { from: "patch" });
365
+ if (params instanceof FormData) {
366
+ opt.headers = { ...(opt.headers ?? {}), "Content-Type": "multipart/form-data" };
367
+ _params = objToFormData(_params);
368
+ }
369
+ this.axios
370
+ .patch(apiUrl, _params, opt)
371
+ .then((response) => {
372
+ this.handleRes(
373
+ response,
374
+ (res) => {
375
+ if (this.patchResMap) {
376
+ res = this.patchResMap(res);
377
+ }
378
+ resolve(res);
379
+ },
380
+ reject,
381
+ );
382
+ })
383
+ .catch((err) => this.errorHandler(err, reject));
384
+ });
385
+ }
386
+
263
387
  /**
264
388
  * 删除接口
265
389
  * @param {*} config axios.delete config 参数,
@@ -455,46 +579,6 @@ export function checkNetwork() {
455
579
  return !noNetwork;
456
580
  }
457
581
 
458
- function setDefaultAxios(ax) {
459
- if (ax) {
460
- _$Temp.axios = ax;
461
- }
462
- }
463
-
464
- export function setDefaultErrMsg(msg) {
465
- if (msg) {
466
- _$Temp.defaultErrMsg = msg;
467
- }
468
- }
469
-
470
- export function setNetworkErrMsg(msg) {
471
- if (msg) {
472
- _$Temp.networkErrMsg = msg;
473
- }
474
- }
475
-
476
- export function objToFormData(data) {
477
- if (data instanceof FormData) {
478
- return data;
479
- }
480
- const formData = new FormData();
481
- Object.keys(data)?.forEach((key) => {
482
- formData.set(key, data[key]);
483
- });
484
- return formData;
485
- }
486
-
487
- export function formDataToObj(formData) {
488
- if (!(formData instanceof FormData)) {
489
- return formData;
490
- }
491
- const tempData = {};
492
- for (const [key, value] of formData.entries()) {
493
- tempData[key] = value;
494
- }
495
- return tempData;
496
- }
497
-
498
- export { axios, DataModel, setDefaultAxios };
582
+ export { axios, DataModel, formDataToObj, objToFormData, setDefaultAxios, setDefaultErrMsg, setNetworkErrMsg };
499
583
 
500
584
  export default DataModel;
package/src/utils.js ADDED
@@ -0,0 +1,92 @@
1
+ /** 默认错误提示文案 */
2
+ const DEFAULT_MSG = "未知错误";
3
+ /** 网络异常提示文案 */
4
+ const NETWORK_MSG = "网络异常,请检查网络是否开启";
5
+
6
+ /** 暂存相关变量 */
7
+ export const _$Temp = {
8
+ defaultErrMsg: DEFAULT_MSG,
9
+ networkErrMsg: NETWORK_MSG,
10
+ };
11
+
12
+ /**
13
+ * 设置默认的 axios
14
+ * @param {*} ax
15
+ */
16
+ export function setDefaultAxios(ax) {
17
+ if (ax) {
18
+ _$Temp.axios = ax;
19
+ }
20
+ }
21
+
22
+ /**
23
+ * 设置默认的错误提示文案
24
+ * @param {*} ax
25
+ */
26
+ export function setDefaultErrMsg(msg) {
27
+ if (msg) {
28
+ _$Temp.defaultErrMsg = msg;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * 设置默认的网络异常提示文案
34
+ * @param {*} ax
35
+ */
36
+ export function setNetworkErrMsg(msg) {
37
+ if (msg) {
38
+ _$Temp.networkErrMsg = msg;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * 检测网络状态
44
+ * @param {*} errMsg 网络异常消息
45
+ * @returns
46
+ */
47
+ export function checkNetwork() {
48
+ if (!navigator) {
49
+ return true;
50
+ }
51
+ if (navigator.onLine === false) {
52
+ return false;
53
+ }
54
+ const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
55
+ if (!connection) {
56
+ return true;
57
+ }
58
+ const noNetwork = connection?.type === "none" || connection.downlink === 0 || connection.effectiveType === null;
59
+ return !noNetwork;
60
+ }
61
+
62
+ /**
63
+ * 对象转 FormData 格式
64
+ * @param {Object} data
65
+ * @returns
66
+ */
67
+ export function objToFormData(data) {
68
+ if (data instanceof FormData) {
69
+ return data;
70
+ }
71
+ const formData = new FormData();
72
+ Object.keys(data)?.forEach((key) => {
73
+ formData.set(key, data[key]);
74
+ });
75
+ return formData;
76
+ }
77
+
78
+ /**
79
+ * FormData 转对象
80
+ * @param {FormData} formData
81
+ * @returns
82
+ */
83
+ export function formDataToObj(formData) {
84
+ if (!(formData instanceof FormData)) {
85
+ return formData;
86
+ }
87
+ const tempData = {};
88
+ for (const [key, value] of formData.entries()) {
89
+ tempData[key] = value;
90
+ }
91
+ return tempData;
92
+ }