@kevisual/query 0.0.40 → 0.0.42

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/dist/query.js CHANGED
@@ -1,384 +1,303 @@
1
- const isTextForContentType = (contentType) => {
2
- if (!contentType)
3
- return false;
4
- const textTypes = ['text/', 'xml', 'html', 'javascript', 'css', 'csv', 'plain', 'x-www-form-urlencoded', 'md'];
5
- return textTypes.some((type) => contentType.includes(type));
1
+ // src/adapter.ts
2
+ var isTextForContentType = (contentType) => {
3
+ if (!contentType)
4
+ return false;
5
+ const textTypes = ["text/", "xml", "html", "javascript", "css", "csv", "plain", "x-www-form-urlencoded", "md"];
6
+ return textTypes.some((type) => contentType.includes(type));
6
7
  };
7
- /**
8
- *
9
- * @param opts
10
- * @param overloadOpts 覆盖fetch的默认配置
11
- * @returns
12
- */
13
- const adapter = async (opts = {}, overloadOpts) => {
14
- const controller = new AbortController();
15
- const signal = controller.signal;
16
- const isPostFile = opts.isPostFile || false; // 是否为文件上传
17
- let responseType = opts.responseType || 'json'; // 响应类型
18
- if (opts.isBlob) {
19
- responseType = 'blob';
20
- }
21
- else if (opts.isText) {
22
- responseType = 'text';
23
- }
24
- const timeout = opts.timeout || 60000 * 3; // 默认超时时间为 60s * 3
25
- const timer = setTimeout(() => {
26
- controller.abort();
27
- }, timeout);
28
- let method = overloadOpts?.method || opts?.method || 'POST';
29
- let headers = { ...opts?.headers, ...overloadOpts?.headers };
30
- let origin = '';
31
- let url;
32
- if (opts?.url?.startsWith('http')) {
33
- url = new URL(opts.url);
34
- }
35
- else {
36
- origin = window?.location?.origin || 'http://localhost:51515';
37
- url = new URL(opts?.url || '', origin);
38
- }
39
- const isGet = method === 'GET';
40
- const oldSearchParams = url.searchParams;
41
- if (isGet) {
42
- let searchParams = new URLSearchParams({ ...Object.fromEntries(oldSearchParams), ...opts?.params, ...opts?.body });
43
- url.search = searchParams.toString();
44
- }
45
- else {
46
- const params = {
47
- ...Object.fromEntries(oldSearchParams),
48
- ...opts.params,
49
- };
50
- const searchParams = new URLSearchParams(params);
51
- if (typeof opts.body === 'object' && opts.body !== null) {
52
- // 浏览器环境下,自动将 body 中的 path 和 key 提取到查询参数中, 更容易排查问题
53
- let body = opts.body || {};
54
- if (!params.path && body?.path) {
55
- searchParams.set('path', body.path);
56
- if (body?.key) {
57
- searchParams.set('key', body.key);
58
- }
59
- }
8
+ var adapter = async (opts = {}, overloadOpts) => {
9
+ const controller = new AbortController;
10
+ const signal = controller.signal;
11
+ const isPostFile = opts.isPostFile || false;
12
+ let responseType = opts.responseType || "json";
13
+ if (opts.isBlob) {
14
+ responseType = "blob";
15
+ } else if (opts.isText) {
16
+ responseType = "text";
17
+ }
18
+ const timeout = opts.timeout || 60000 * 3;
19
+ const timer = setTimeout(() => {
20
+ controller.abort();
21
+ }, timeout);
22
+ let method = overloadOpts?.method || opts?.method || "POST";
23
+ let headers = { ...opts?.headers, ...overloadOpts?.headers };
24
+ let origin = "";
25
+ let url;
26
+ if (opts?.url?.startsWith("http")) {
27
+ url = new URL(opts.url);
28
+ } else {
29
+ origin = globalThis?.location?.origin || "http://localhost:51515";
30
+ url = new URL(opts?.url || "", origin);
31
+ }
32
+ const isGet = method === "GET";
33
+ const oldSearchParams = url.searchParams;
34
+ if (isGet) {
35
+ let searchParams = new URLSearchParams({ ...Object.fromEntries(oldSearchParams), ...opts?.params, ...opts?.body });
36
+ url.search = searchParams.toString();
37
+ } else {
38
+ const params = {
39
+ ...Object.fromEntries(oldSearchParams),
40
+ ...opts.params
41
+ };
42
+ const searchParams = new URLSearchParams(params);
43
+ if (typeof opts.body === "object" && opts.body !== null) {
44
+ let body2 = opts.body || {};
45
+ if (!params.path && body2?.path) {
46
+ searchParams.set("path", body2.path);
47
+ if (body2?.key) {
48
+ searchParams.set("key", body2.key);
60
49
  }
61
- url.search = searchParams.toString();
50
+ }
62
51
  }
63
- let body = undefined;
64
- if (isGet) {
65
- body = undefined;
52
+ url.search = searchParams.toString();
53
+ }
54
+ let body = undefined;
55
+ if (isGet) {
56
+ body = undefined;
57
+ } else if (isPostFile) {
58
+ body = opts.body;
59
+ } else {
60
+ if (opts.body && typeof opts.body === "object" && !(opts.body instanceof FormData)) {
61
+ headers = {
62
+ "Content-Type": "application/json",
63
+ ...headers
64
+ };
65
+ body = JSON.stringify(opts.body);
66
66
  }
67
- else if (isPostFile) {
68
- body = opts.body; // 如果是文件上传,直接使用 FormData
67
+ }
68
+ return fetch(url, {
69
+ method: method.toUpperCase(),
70
+ signal,
71
+ body,
72
+ ...overloadOpts,
73
+ headers
74
+ }).then(async (response) => {
75
+ const contentType = response.headers.get("Content-Type");
76
+ if (responseType === "blob") {
77
+ return await response.blob();
69
78
  }
70
- else {
71
- if (opts.body && typeof opts.body === 'object' && !(opts.body instanceof FormData)) {
72
- headers = {
73
- 'Content-Type': 'application/json',
74
- ...headers,
75
- };
76
- body = JSON.stringify(opts.body); // 否则将对象转换为 JSON 字符串
77
- }
79
+ const isText = responseType === "text";
80
+ const isJson = contentType && contentType.includes("application/json");
81
+ if (isJson && !isText) {
82
+ return await response.json();
83
+ } else if (isTextForContentType(contentType)) {
84
+ return {
85
+ code: response.status,
86
+ status: response.status,
87
+ data: await response.text()
88
+ };
89
+ } else {
90
+ return response;
78
91
  }
79
- return fetch(url, {
80
- method: method.toUpperCase(),
81
- signal,
82
- body: body,
83
- ...overloadOpts,
84
- headers: headers,
85
- })
86
- .then(async (response) => {
87
- // 获取 Content-Type 头部信息
88
- const contentType = response.headers.get('Content-Type');
89
- if (responseType === 'blob') {
90
- return await response.blob(); // 直接返回 Blob 对象
91
- }
92
- const isText = responseType === 'text';
93
- const isJson = contentType && contentType.includes('application/json');
94
- // 判断返回的数据类型
95
- if (isJson && !isText) {
96
- return await response.json(); // 解析为 JSON
97
- }
98
- else if (isTextForContentType(contentType)) {
99
- return {
100
- code: response.status,
101
- status: response.status,
102
- data: await response.text(), // 直接返回文本内容
103
- };
104
- }
105
- else {
106
- return response;
107
- }
108
- })
109
- .catch((err) => {
110
- if (err.name === 'AbortError') {
111
- return {
112
- code: 408,
113
- message: '请求超时',
114
- };
115
- }
116
- return {
117
- code: 500,
118
- message: err.message || '网络错误',
119
- };
120
- })
121
- .finally(() => {
122
- clearTimeout(timer);
123
- });
92
+ }).catch((err) => {
93
+ if (err.name === "AbortError") {
94
+ return {
95
+ code: 408,
96
+ message: "请求超时"
97
+ };
98
+ }
99
+ return {
100
+ code: 500,
101
+ message: err.message || "网络错误"
102
+ };
103
+ }).finally(() => {
104
+ clearTimeout(timer);
105
+ });
124
106
  };
125
107
 
126
- /**
127
- * 设置基础响应, 设置 success 和 showError,
128
- * success code 是否等于 200
129
- * showError 如果 success 为 false 且 noMsg 为 false, 则调用 showError
130
- * @param res 响应
131
- */
132
- const setBaseResponse = (res) => {
133
- res.success = res.code === 200;
134
- /**
135
- * 显示错误
136
- * @param fn 错误处理函数
137
- */
138
- res.showError = (fn) => {
139
- if (!res.success && !res.noMsg) {
140
- fn?.();
141
- }
142
- };
143
- return res;
108
+ // src/query.ts
109
+ var setBaseResponse = (res) => {
110
+ res.success = res.code === 200;
111
+ res.showError = (fn) => {
112
+ if (!res.success && !res.noMsg) {
113
+ fn?.();
114
+ }
115
+ };
116
+ return res;
144
117
  };
145
- const wrapperError = ({ code, message }) => {
146
- const result = {
147
- code: code || 500,
148
- success: false,
149
- message: message || 'api request error',
150
- showError: (fn) => {
151
- //
152
- },
153
- noMsg: true,
154
- };
155
- return result;
118
+ var wrapperError = ({ code, message }) => {
119
+ const result = {
120
+ code: code || 500,
121
+ success: false,
122
+ message: message || "api request error",
123
+ showError: (fn) => {},
124
+ noMsg: true
125
+ };
126
+ return result;
156
127
  };
157
- /**
158
- * const query = new Query();
159
- * const res = await query.post({
160
- * path: 'demo',
161
- * key: '1',
162
- * });
163
- *
164
- * U是参数 V是返回值
165
- */
128
+
166
129
  class Query {
167
- adapter;
168
- url;
169
- /**
170
- * 请求前处理函数
171
- */
172
- beforeRequest;
173
- /**
174
- * 请求后处理函数
175
- */
176
- afterResponse;
177
- headers;
178
- timeout;
179
- /**
180
- * 需要突然停止请求,比如401的时候
181
- */
182
- stop;
183
- // 默认不使用ws
184
- qws;
185
- /**
186
- * 默认是 /client/router或者 默认是 /api/router
187
- */
188
- isClient = false;
189
- constructor(opts) {
190
- this.adapter = opts?.adapter || adapter;
191
- const defaultURL = opts?.isClient ? '/client/router' : '/api/router';
192
- this.url = opts?.url || defaultURL;
193
- this.headers = opts?.headers || {
194
- 'Content-Type': 'application/json',
195
- };
196
- this.timeout = opts?.timeout || 60000 * 3; // 默认超时时间为 60s * 3
197
- if (opts?.beforeRequest) {
198
- this.beforeRequest = opts.beforeRequest;
199
- }
200
- else {
201
- this.beforeRequest = async (opts) => {
202
- const token = globalThis?.localStorage?.getItem('token');
203
- if (token) {
204
- opts.headers = {
205
- ...opts.headers,
206
- Authorization: `Bearer ${token}`,
207
- };
208
- }
209
- return opts;
210
- };
130
+ adapter;
131
+ url;
132
+ beforeRequest;
133
+ afterResponse;
134
+ headers;
135
+ timeout;
136
+ stop;
137
+ qws;
138
+ isClient = false;
139
+ constructor(opts) {
140
+ this.adapter = opts?.adapter || adapter;
141
+ const defaultURL = opts?.isClient ? "/client/router" : "/api/router";
142
+ this.url = opts?.url || defaultURL;
143
+ this.headers = opts?.headers || {
144
+ "Content-Type": "application/json"
145
+ };
146
+ this.timeout = opts?.timeout || 60000 * 3;
147
+ if (opts?.beforeRequest) {
148
+ this.beforeRequest = opts.beforeRequest;
149
+ } else {
150
+ this.beforeRequest = async (opts2) => {
151
+ const token = globalThis?.localStorage?.getItem("token");
152
+ if (token) {
153
+ opts2.headers = {
154
+ ...opts2.headers,
155
+ Authorization: `Bearer ${token}`
156
+ };
211
157
  }
158
+ return opts2;
159
+ };
212
160
  }
213
- setQueryWs(qws) {
214
- this.qws = qws;
215
- }
216
- /**
217
- * 突然停止请求
218
- */
219
- setStop(stop) {
220
- this.stop = stop;
161
+ }
162
+ setQueryWs(qws) {
163
+ this.qws = qws;
164
+ }
165
+ setStop(stop) {
166
+ this.stop = stop;
167
+ }
168
+ async get(params, options) {
169
+ return this.post(params, options);
170
+ }
171
+ async post(body, options) {
172
+ const url = options?.url || this.url;
173
+ console.log("query post", url, body, options);
174
+ const { headers, adapter: adapter2, beforeRequest, afterResponse, timeout, ...rest } = options || {};
175
+ const _headers = { ...this.headers, ...headers };
176
+ const _adapter = adapter2 || this.adapter;
177
+ const _beforeRequest = beforeRequest || this.beforeRequest;
178
+ const _afterResponse = afterResponse || this.afterResponse;
179
+ const _timeout = timeout || this.timeout;
180
+ const req = {
181
+ url,
182
+ headers: _headers,
183
+ body,
184
+ timeout: _timeout,
185
+ ...rest
186
+ };
187
+ try {
188
+ if (_beforeRequest) {
189
+ const res = await _beforeRequest(req);
190
+ if (res === false) {
191
+ return wrapperError({
192
+ code: 500,
193
+ message: "request is cancel",
194
+ req
195
+ });
196
+ }
197
+ }
198
+ } catch (e) {
199
+ console.error("request beforeFn error", e, req);
200
+ return wrapperError({
201
+ code: 500,
202
+ message: "api request beforeFn error",
203
+ req
204
+ });
221
205
  }
222
- /**
223
- * 发送 get 请求,转到 post 请求
224
- * T是请求类型自定义
225
- * S是返回类型自定义
226
- * @param params 请求参数
227
- * @param options 请求配置
228
- * @returns 请求结果
229
- */
230
- async get(params, options) {
231
- return this.post(params, options);
206
+ if (this.stop && !options?.noStop) {
207
+ const that = this;
208
+ await new Promise((resolve) => {
209
+ let timer = 0;
210
+ const detect = setInterval(() => {
211
+ if (!that.stop) {
212
+ clearInterval(detect);
213
+ resolve(true);
214
+ }
215
+ timer++;
216
+ if (timer > 30) {
217
+ console.error("request stop: timeout", req.url, timer);
218
+ }
219
+ }, 1000);
220
+ });
232
221
  }
233
- /**
234
- * 发送 post 请求
235
- * T是请求类型自定义
236
- * S是返回类型自定义
237
- * @param body 请求体
238
- * @param options 请求配置
239
- * @returns 请求结果
240
- */
241
- async post(body, options) {
242
- const url = options?.url || this.url;
243
- const { headers, adapter, beforeRequest, afterResponse, timeout, ...rest } = options || {};
244
- const _headers = { ...this.headers, ...headers };
245
- const _adapter = adapter || this.adapter;
246
- const _beforeRequest = beforeRequest || this.beforeRequest;
247
- const _afterResponse = afterResponse || this.afterResponse;
248
- const _timeout = timeout || this.timeout;
249
- const req = {
250
- url: url,
251
- headers: _headers,
252
- body,
253
- timeout: _timeout,
254
- ...rest,
255
- };
256
- try {
257
- if (_beforeRequest) {
258
- const res = await _beforeRequest(req);
259
- if (res === false) {
260
- return wrapperError({
261
- code: 500,
262
- message: 'request is cancel',
263
- // @ts-ignore
264
- req: req,
265
- });
266
- }
267
- }
222
+ return _adapter(req).then(async (res) => {
223
+ try {
224
+ if (_afterResponse) {
225
+ return await _afterResponse(res, {
226
+ req,
227
+ res,
228
+ fetch: adapter2
229
+ });
268
230
  }
269
- catch (e) {
270
- console.error('request beforeFn error', e, req);
271
- return wrapperError({
272
- code: 500,
273
- message: 'api request beforeFn error'});
274
- }
275
- if (this.stop && !options?.noStop) {
276
- const that = this;
277
- await new Promise((resolve) => {
278
- let timer = 0;
279
- const detect = setInterval(() => {
280
- if (!that.stop) {
281
- clearInterval(detect);
282
- resolve(true);
283
- }
284
- timer++;
285
- if (timer > 30) {
286
- console.error('request stop: timeout', req.url, timer);
287
- }
288
- }, 1000);
289
- });
290
- }
291
- return _adapter(req).then(async (res) => {
292
- try {
293
- if (_afterResponse) {
294
- return await _afterResponse(res, {
295
- req,
296
- res,
297
- fetch: adapter,
298
- });
299
- }
300
- return res;
301
- }
302
- catch (e) {
303
- console.error('request afterFn error', e, req);
304
- return wrapperError({
305
- code: 500,
306
- message: 'api request afterFn error'});
307
- }
231
+ return res;
232
+ } catch (e) {
233
+ console.error("request afterFn error", e, req);
234
+ return wrapperError({
235
+ code: 500,
236
+ message: "api request afterFn error",
237
+ req
308
238
  });
239
+ }
240
+ });
241
+ }
242
+ before(fn) {
243
+ this.beforeRequest = fn;
244
+ }
245
+ after(fn) {
246
+ this.afterResponse = fn;
247
+ }
248
+ async fetchText(urlOrOptions, options) {
249
+ let _options = { ...options };
250
+ if (typeof urlOrOptions === "string" && !_options.url) {
251
+ _options.url = urlOrOptions;
309
252
  }
310
- /**
311
- * 设置请求前处理,设置请求前处理函数
312
- * @param fn 处理函数
313
- */
314
- before(fn) {
315
- this.beforeRequest = fn;
316
- }
317
- /**
318
- * 设置请求后处理,设置请求后处理函数
319
- * @param fn 处理函数
320
- */
321
- after(fn) {
322
- this.afterResponse = fn;
253
+ if (typeof urlOrOptions === "object") {
254
+ _options = { ...urlOrOptions, ..._options };
323
255
  }
324
- async fetchText(urlOrOptions, options) {
325
- let _options = { ...options };
326
- if (typeof urlOrOptions === 'string' && !_options.url) {
327
- _options.url = urlOrOptions;
328
- }
329
- if (typeof urlOrOptions === 'object') {
330
- _options = { ...urlOrOptions, ..._options };
331
- }
332
- const res = await adapter({
333
- method: 'GET',
334
- ..._options,
335
- headers: {
336
- ...this.headers,
337
- ...(_options?.headers || {}),
338
- },
339
- });
340
- if (res && !res.code) {
341
- return {
342
- code: 200,
343
- data: res,
344
- };
345
- }
346
- return res;
256
+ const res = await adapter({
257
+ method: "GET",
258
+ ..._options,
259
+ headers: {
260
+ ...this.headers,
261
+ ..._options?.headers || {}
262
+ }
263
+ });
264
+ if (res && !res.code) {
265
+ return {
266
+ code: 200,
267
+ data: res
268
+ };
347
269
  }
270
+ return res;
271
+ }
348
272
  }
349
273
  class BaseQuery {
350
- query;
351
- queryDefine;
352
- constructor(opts) {
353
- if (opts?.clientQuery) {
354
- this.query = opts.clientQuery;
355
- }
356
- else {
357
- this.query = opts?.query;
358
- }
359
- if (opts.queryDefine) {
360
- this.queryDefine = opts.queryDefine;
361
- this.queryDefine.query = this.query;
362
- }
274
+ query;
275
+ queryDefine;
276
+ constructor(opts) {
277
+ if (opts?.clientQuery) {
278
+ this.query = opts.clientQuery;
279
+ } else {
280
+ this.query = opts?.query;
363
281
  }
364
- get chain() {
365
- return this.queryDefine.queryChain;
366
- }
367
- post(data, options) {
368
- return this.query.post(data, options);
369
- }
370
- get(data, options) {
371
- return this.query.get(data, options);
372
- }
373
- }
374
- /**
375
- * @deprecated
376
- * 前端调用后端QueryRouter, 默认路径 /client/router
377
- */
378
- class ClientQuery extends Query {
379
- constructor(opts) {
380
- super({ ...opts, url: opts?.url || '/client/router' });
282
+ if (opts.queryDefine) {
283
+ this.queryDefine = opts.queryDefine;
284
+ this.queryDefine.query = this.query;
381
285
  }
286
+ }
287
+ get chain() {
288
+ return this.queryDefine.queryChain;
289
+ }
290
+ post(data, options) {
291
+ return this.query.post(data, options);
292
+ }
293
+ get(data, options) {
294
+ return this.query.get(data, options);
295
+ }
382
296
  }
383
-
384
- export { BaseQuery, ClientQuery, Query, adapter, setBaseResponse, wrapperError };
297
+ export {
298
+ wrapperError,
299
+ setBaseResponse,
300
+ adapter,
301
+ Query,
302
+ BaseQuery
303
+ };