@kevisual/query 0.0.39 → 0.0.41

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,379 +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.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
- headers = {
72
- 'Content-Type': 'application/json',
73
- ...headers,
74
- };
75
- body = JSON.stringify(opts.body); // 否则将对象转换为 JSON 字符串
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;
76
91
  }
77
- return fetch(url, {
78
- method: method.toUpperCase(),
79
- signal,
80
- body: body,
81
- ...overloadOpts,
82
- headers: headers,
83
- })
84
- .then(async (response) => {
85
- // 获取 Content-Type 头部信息
86
- const contentType = response.headers.get('Content-Type');
87
- if (responseType === 'blob') {
88
- return await response.blob(); // 直接返回 Blob 对象
89
- }
90
- const isText = responseType === 'text';
91
- const isJson = contentType && contentType.includes('application/json');
92
- // 判断返回的数据类型
93
- if (isJson && !isText) {
94
- return await response.json(); // 解析为 JSON
95
- }
96
- else if (isTextForContentType(contentType)) {
97
- return {
98
- code: response.status,
99
- status: response.status,
100
- data: await response.text(), // 直接返回文本内容
101
- };
102
- }
103
- else {
104
- return response;
105
- }
106
- })
107
- .catch((err) => {
108
- if (err.name === 'AbortError') {
109
- return {
110
- code: 408,
111
- message: '请求超时',
112
- };
113
- }
114
- return {
115
- code: 500,
116
- message: err.message || '网络错误',
117
- };
118
- })
119
- .finally(() => {
120
- clearTimeout(timer);
121
- });
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
+ });
122
106
  };
123
107
 
124
- /**
125
- * 设置基础响应, 设置 success 和 showError,
126
- * success code 是否等于 200
127
- * showError 如果 success 为 false 且 noMsg 为 false, 则调用 showError
128
- * @param res 响应
129
- */
130
- const setBaseResponse = (res) => {
131
- res.success = res.code === 200;
132
- /**
133
- * 显示错误
134
- * @param fn 错误处理函数
135
- */
136
- res.showError = (fn) => {
137
- if (!res.success && !res.noMsg) {
138
- fn?.();
139
- }
140
- };
141
- 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;
142
117
  };
143
- const wrapperError = ({ code, message }) => {
144
- const result = {
145
- code: code || 500,
146
- success: false,
147
- message: message || 'api request error',
148
- showError: (fn) => {
149
- //
150
- },
151
- noMsg: true,
152
- };
153
- 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;
154
127
  };
155
- /**
156
- * const query = new Query();
157
- * const res = await query.post({
158
- * path: 'demo',
159
- * key: '1',
160
- * });
161
- *
162
- * U是参数 V是返回值
163
- */
128
+
164
129
  class Query {
165
- adapter;
166
- url;
167
- /**
168
- * 请求前处理函数
169
- */
170
- beforeRequest;
171
- /**
172
- * 请求后处理函数
173
- */
174
- afterResponse;
175
- headers;
176
- timeout;
177
- /**
178
- * 需要突然停止请求,比如401的时候
179
- */
180
- stop;
181
- // 默认不使用ws
182
- qws;
183
- isClient = false;
184
- constructor(opts) {
185
- this.adapter = opts?.adapter || adapter;
186
- const defaultURL = opts?.isClient ? '/client/router' : '/api/router';
187
- this.url = opts?.url || defaultURL;
188
- this.headers = opts?.headers || {
189
- 'Content-Type': 'application/json',
190
- };
191
- this.timeout = opts?.timeout || 60000 * 3; // 默认超时时间为 60s * 3
192
- if (opts.beforeRequest) {
193
- this.beforeRequest = opts.beforeRequest;
194
- }
195
- else {
196
- this.beforeRequest = async (opts) => {
197
- const token = globalThis?.localStorage?.getItem('token');
198
- if (token) {
199
- opts.headers = {
200
- ...opts.headers,
201
- Authorization: `Bearer ${token}`,
202
- };
203
- }
204
- return opts;
205
- };
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
+ };
206
157
  }
158
+ return opts2;
159
+ };
207
160
  }
208
- setQueryWs(qws) {
209
- this.qws = qws;
210
- }
211
- /**
212
- * 突然停止请求
213
- */
214
- setStop(stop) {
215
- 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
+ });
216
205
  }
217
- /**
218
- * 发送 get 请求,转到 post 请求
219
- * T是请求类型自定义
220
- * S是返回类型自定义
221
- * @param params 请求参数
222
- * @param options 请求配置
223
- * @returns 请求结果
224
- */
225
- async get(params, options) {
226
- 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
+ });
227
221
  }
228
- /**
229
- * 发送 post 请求
230
- * T是请求类型自定义
231
- * S是返回类型自定义
232
- * @param body 请求体
233
- * @param options 请求配置
234
- * @returns 请求结果
235
- */
236
- async post(body, options) {
237
- const url = options?.url || this.url;
238
- const { headers, adapter, beforeRequest, afterResponse, timeout, ...rest } = options || {};
239
- const _headers = { ...this.headers, ...headers };
240
- const _adapter = adapter || this.adapter;
241
- const _beforeRequest = beforeRequest || this.beforeRequest;
242
- const _afterResponse = afterResponse || this.afterResponse;
243
- const _timeout = timeout || this.timeout;
244
- const req = {
245
- url: url,
246
- headers: _headers,
247
- body,
248
- timeout: _timeout,
249
- ...rest,
250
- };
251
- try {
252
- if (_beforeRequest) {
253
- const res = await _beforeRequest(req);
254
- if (res === false) {
255
- return wrapperError({
256
- code: 500,
257
- message: 'request is cancel',
258
- // @ts-ignore
259
- req: req,
260
- });
261
- }
262
- }
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
+ });
263
230
  }
264
- catch (e) {
265
- console.error('request beforeFn error', e, req);
266
- return wrapperError({
267
- code: 500,
268
- message: 'api request beforeFn error'});
269
- }
270
- if (this.stop && !options?.noStop) {
271
- const that = this;
272
- await new Promise((resolve) => {
273
- let timer = 0;
274
- const detect = setInterval(() => {
275
- if (!that.stop) {
276
- clearInterval(detect);
277
- resolve(true);
278
- }
279
- timer++;
280
- if (timer > 30) {
281
- console.error('request stop: timeout', req.url, timer);
282
- }
283
- }, 1000);
284
- });
285
- }
286
- return _adapter(req).then(async (res) => {
287
- try {
288
- if (_afterResponse) {
289
- return await _afterResponse(res, {
290
- req,
291
- res,
292
- fetch: adapter,
293
- });
294
- }
295
- return res;
296
- }
297
- catch (e) {
298
- console.error('request afterFn error', e, req);
299
- return wrapperError({
300
- code: 500,
301
- message: 'api request afterFn error'});
302
- }
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
303
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;
304
252
  }
305
- /**
306
- * 设置请求前处理,设置请求前处理函数
307
- * @param fn 处理函数
308
- */
309
- before(fn) {
310
- this.beforeRequest = fn;
311
- }
312
- /**
313
- * 设置请求后处理,设置请求后处理函数
314
- * @param fn 处理函数
315
- */
316
- after(fn) {
317
- this.afterResponse = fn;
253
+ if (typeof urlOrOptions === "object") {
254
+ _options = { ...urlOrOptions, ..._options };
318
255
  }
319
- async fetchText(urlOrOptions, options) {
320
- let _options = { ...options };
321
- if (typeof urlOrOptions === 'string' && !_options.url) {
322
- _options.url = urlOrOptions;
323
- }
324
- if (typeof urlOrOptions === 'object') {
325
- _options = { ...urlOrOptions, ..._options };
326
- }
327
- const res = await adapter({
328
- method: 'GET',
329
- ..._options,
330
- headers: {
331
- ...this.headers,
332
- ...(_options?.headers || {}),
333
- },
334
- });
335
- if (res && !res.code) {
336
- return {
337
- code: 200,
338
- data: res,
339
- };
340
- }
341
- 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
+ };
342
269
  }
270
+ return res;
271
+ }
343
272
  }
344
273
  class BaseQuery {
345
- query;
346
- queryDefine;
347
- constructor(opts) {
348
- if (opts?.clientQuery) {
349
- this.query = opts.clientQuery;
350
- }
351
- else {
352
- this.query = opts?.query;
353
- }
354
- if (opts.queryDefine) {
355
- this.queryDefine = opts.queryDefine;
356
- this.queryDefine.query = this.query;
357
- }
274
+ query;
275
+ queryDefine;
276
+ constructor(opts) {
277
+ if (opts?.clientQuery) {
278
+ this.query = opts.clientQuery;
279
+ } else {
280
+ this.query = opts?.query;
358
281
  }
359
- get chain() {
360
- return this.queryDefine.queryChain;
361
- }
362
- post(data, options) {
363
- return this.query.post(data, options);
364
- }
365
- get(data, options) {
366
- return this.query.get(data, options);
367
- }
368
- }
369
- /**
370
- * @deprecated
371
- * 前端调用后端QueryRouter, 默认路径 /client/router
372
- */
373
- class ClientQuery extends Query {
374
- constructor(opts) {
375
- super({ ...opts, url: opts?.url || '/client/router' });
282
+ if (opts.queryDefine) {
283
+ this.queryDefine = opts.queryDefine;
284
+ this.queryDefine.query = this.query;
376
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
+ }
377
296
  }
378
-
379
- export { BaseQuery, ClientQuery, Query, adapter, setBaseResponse, wrapperError };
297
+ export {
298
+ wrapperError,
299
+ setBaseResponse,
300
+ adapter,
301
+ Query,
302
+ BaseQuery
303
+ };