@zwa73/utils 1.0.218 → 1.0.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- export { Piper, Stream, Hbs, BridgeInterface, Bridge, SmartCache, DListMiddleNode, DLinkedList, PromoseQueueOption, PromiseQueue } from "@zwa73/js-utils";
1
+ export { BridgeInterface, Bridge, Hbs, DListMiddleNode, DListHeadNode, DListTailNode, DListNode, DListMaybeNode, DLinkedList, Piper, PromoseQueueOption, PromiseQueue, SmartCache, Stream } from "@zwa73/js-utils";
package/dist/UtilClass.js CHANGED
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PromiseQueue = exports.DLinkedList = exports.SmartCache = exports.Bridge = exports.Hbs = exports.Stream = exports.Piper = void 0;
3
+ exports.Stream = exports.SmartCache = exports.PromiseQueue = exports.Piper = exports.DLinkedList = exports.Hbs = exports.Bridge = void 0;
4
4
  //#region UtilClass转导
5
5
  var js_utils_1 = require("@zwa73/js-utils");
6
- Object.defineProperty(exports, "Piper", { enumerable: true, get: function () { return js_utils_1.Piper; } });
7
- Object.defineProperty(exports, "Stream", { enumerable: true, get: function () { return js_utils_1.Stream; } });
8
- Object.defineProperty(exports, "Hbs", { enumerable: true, get: function () { return js_utils_1.Hbs; } });
9
6
  Object.defineProperty(exports, "Bridge", { enumerable: true, get: function () { return js_utils_1.Bridge; } });
10
- Object.defineProperty(exports, "SmartCache", { enumerable: true, get: function () { return js_utils_1.SmartCache; } });
7
+ Object.defineProperty(exports, "Hbs", { enumerable: true, get: function () { return js_utils_1.Hbs; } });
11
8
  Object.defineProperty(exports, "DLinkedList", { enumerable: true, get: function () { return js_utils_1.DLinkedList; } });
9
+ Object.defineProperty(exports, "Piper", { enumerable: true, get: function () { return js_utils_1.Piper; } });
12
10
  Object.defineProperty(exports, "PromiseQueue", { enumerable: true, get: function () { return js_utils_1.PromiseQueue; } });
11
+ Object.defineProperty(exports, "SmartCache", { enumerable: true, get: function () { return js_utils_1.SmartCache; } });
12
+ Object.defineProperty(exports, "Stream", { enumerable: true, get: function () { return js_utils_1.Stream; } });
13
13
  //#endregion
@@ -279,23 +279,27 @@ var UtilFT;
279
279
  * @returns 文件名路径数组
280
280
  */
281
281
  async function fileSearchRegex(dir, traitRegex, opt) {
282
- const recursive = opt?.recursive ?? true;
283
- const outArray = [];
284
- const subFiles = await fs.promises.readdir(dir, { withFileTypes: true });
282
+ const fixopt = Object.assign({ recursive: true }, opt);
285
283
  //如果使用 g 会导致 RegExp.lastIndex 更改, 将会导致匹配错误
286
284
  const regex = new RegExp(traitRegex);
287
- await Promise.all(subFiles.map(async (subFile) => {
288
- const subFilePath = pathe_1.default.join(dir, subFile.name);
289
- //判断是否是文件夹,递归调用
290
- if (subFile.isDirectory()) {
291
- if (recursive)
292
- outArray.push(...await UtilFT.fileSearchRegex(pathe_1.default.join(subFilePath, pathe_1.default.sep), traitRegex));
293
- return;
294
- }
295
- if (regex.test(subFilePath))
296
- outArray.push(subFilePath);
297
- }));
298
- return outArray.map((filePath) => pathe_1.default.normalize(filePath));
285
+ const recursive = async (curPath) => {
286
+ const subDir = pathe_1.default.join(dir, curPath);
287
+ const subFiles = await fs.promises.readdir(subDir, { withFileTypes: true });
288
+ const matchFiles = await Promise.all(subFiles.map(async (subFile) => {
289
+ const subFilePath = pathe_1.default.join(subDir, subFile.name);
290
+ const nextPath = pathe_1.default.join(curPath, subFile.name);
291
+ //判断是否是文件夹,递归调用
292
+ if (subFile.isDirectory() && fixopt.recursive)
293
+ return recursive(nextPath);
294
+ if (regex.test(nextPath))
295
+ return [subFilePath];
296
+ return [undefined];
297
+ }));
298
+ return matchFiles.flat()
299
+ .filter(v => v != undefined)
300
+ .map(fp => pathe_1.default.normalize(fp));
301
+ };
302
+ return recursive('');
299
303
  }
300
304
  UtilFT.fileSearchRegex = fileSearchRegex;
301
305
  /**搜索路径符合正则表达式的文件 同步版本
@@ -306,23 +310,27 @@ var UtilFT;
306
310
  * @returns 文件名路径数组
307
311
  */
308
312
  function fileSearchRegexSync(dir, traitRegex, opt) {
309
- const recursive = opt?.recursive ?? true;
310
- const outArray = [];
311
- const subFiles = fs.readdirSync(dir, { withFileTypes: true });
313
+ const fixopt = Object.assign({ recursive: true }, opt);
312
314
  //如果使用 g 会导致 RegExp.lastIndex 更改, 将会导致匹配错误
313
315
  const regex = new RegExp(traitRegex);
314
- for (const subFile of subFiles) {
315
- const subFilePath = pathe_1.default.join(dir, subFile.name);
316
- //判断是否是文件夹,递归调用
317
- if (subFile.isDirectory()) {
318
- if (recursive)
319
- outArray.push(...fileSearchRegexSync(pathe_1.default.join(subFilePath, pathe_1.default.sep), traitRegex));
320
- continue;
321
- }
322
- if (regex.test(subFilePath))
323
- outArray.push(subFilePath);
324
- }
325
- return outArray.map((filePath) => pathe_1.default.normalize(filePath));
316
+ const recursive = (curPath) => {
317
+ const subDir = pathe_1.default.join(dir, curPath);
318
+ const subFiles = fs.readdirSync(subDir, { withFileTypes: true });
319
+ const matchFiles = subFiles.map(subFile => {
320
+ const subFilePath = pathe_1.default.join(subDir, subFile.name);
321
+ const nextPath = pathe_1.default.join(curPath, subFile.name);
322
+ //判断是否是文件夹,递归调用
323
+ if (subFile.isDirectory() && fixopt.recursive)
324
+ return recursive(nextPath);
325
+ if (regex.test(nextPath))
326
+ return [subFilePath];
327
+ return [undefined];
328
+ });
329
+ return matchFiles.flat()
330
+ .filter(v => v != undefined)
331
+ .map(fp => pathe_1.default.normalize(fp));
332
+ };
333
+ return recursive('');
326
334
  }
327
335
  UtilFT.fileSearchRegexSync = fileSearchRegexSync;
328
336
  /**搜索符合Glob匹配的文件
@@ -2,6 +2,7 @@ import { AnyString, JToken, MPromise, PartialOption, StatusVerifyFn } from "./Ut
2
2
  import http from 'http';
3
3
  import { PromiseRetries } from "./UtilFunctions";
4
4
  import FormData from "form-data";
5
+ import { RequiredOnly } from "@zwa73/js-utils";
5
6
  /**网络请求返回值 */
6
7
  export type RequestResult<T> = {
7
8
  /**响应头 */
@@ -64,48 +65,64 @@ declare const AcceptNoneProc: AcceptProc<undefined, undefined>;
64
65
  type SendParams<P extends SendProc<any>> = P extends SendProc<infer T> ? T : never;
65
66
  /**accept处理的结果 */
66
67
  type ParseResult<P extends AcceptProc<any, any>> = P extends AcceptProc<any, infer T> ? Awaited<T> : never;
67
- /**网络请求工具 */
68
- export declare class UtilCom<D extends Partial<RequestOption> & Required<Pick<RequestOption, 'protocol'>>, S extends SendProc<any>, A extends AcceptProc<any, any>> {
68
+ /**http请求工具 */
69
+ export declare class UtilHttp<D extends Partial<RequestOption> & Required<Pick<RequestOption, 'protocol'>>, S extends SendProc<any>, A extends AcceptProc<any, any>> {
69
70
  private _data;
70
71
  private _send;
71
72
  private _accept;
72
73
  private constructor();
73
74
  /**设为https请求 */
74
- static https(): UtilCom<{
75
+ static https(): UtilHttp<{
75
76
  readonly protocol: "https:";
76
77
  }, SendProc<[]>, AcceptProc<string, RequestResult<string> | undefined>>;
77
78
  /**设为http请求 */
78
- static http(): UtilCom<{
79
+ static http(): UtilHttp<{
79
80
  readonly protocol: "http:";
80
81
  }, SendProc<[]>, AcceptProc<string, RequestResult<string> | undefined>>;
82
+ /**从url创建 */
83
+ static url(urlStr: `${'http:' | 'https:'}//${string}`): UtilHttp<{
84
+ protocol: "http:" | "https:";
85
+ } & {
86
+ hostname: string;
87
+ path: string;
88
+ port: number | undefined;
89
+ }, SendProc<[]>, AcceptProc<string, RequestResult<string> | undefined>>;
81
90
  /**设为get方式的请求 */
82
- get(): UtilCom<D & {
91
+ get(): UtilHttp<D & {
83
92
  method: "GET";
84
93
  }, S, A>;
85
94
  /**设为Post方式的请求 */
86
- post(): UtilCom<D & {
95
+ post(): UtilHttp<D & {
87
96
  method: "POST";
88
97
  }, S, A>;
89
98
  /**补充参数
99
+ * 不会检查必要参数完整性
90
100
  * 将会替换对应字段, 修改headers请用header函数
91
101
  */
92
- option<OPT extends Partial<RequestOption>>(option: OPT): UtilCom<D & OPT, S, A>;
102
+ option<OPT extends Partial<RequestOption>>(option: OPT): UtilHttp<D & OPT, S, A>;
103
+ /**完成参数
104
+ * 会检查必要参数完整性
105
+ * 将会替换对应字段, 修改headers请用header函数
106
+ */
107
+ finalize<OPT extends PartialOption<RequestOption, D>>(option: OPT): UtilHttp<D & OPT, S, A>;
93
108
  /**补充header */
94
- header<HAD extends http.OutgoingHttpHeaders>(headers: HAD): UtilCom<D & {
109
+ header<HAD extends http.OutgoingHttpHeaders>(headers: HAD): UtilHttp<D & {
95
110
  headers: HAD;
96
111
  }, S, A>;
97
112
  /**设置agent */
98
113
  proxyAgent(url: string): this;
99
114
  /**添加一段query */
100
115
  query(data: QueryRequestData): this;
116
+ /**克隆 */
117
+ clone(): UtilHttp<D, S, A>;
101
118
  /**收发皆为json的预设 */
102
- json(): UtilCom<D & {
119
+ json(): UtilHttp<D & {
103
120
  headers: {
104
121
  "Content-Type": "application/json";
105
122
  };
106
123
  }, SendProc<[JToken]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
107
124
  /**收发皆为json的post预设 */
108
- postJson(): UtilCom<D & {
125
+ postJson(): UtilHttp<D & {
109
126
  method: "POST";
110
127
  } & {
111
128
  headers: {
@@ -113,15 +130,15 @@ export declare class UtilCom<D extends Partial<RequestOption> & Required<Pick<Re
113
130
  };
114
131
  }, SendProc<[JToken]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
115
132
  /**无查询参数获取json的get预设 */
116
- getJson(): UtilCom<D & {
133
+ getJson(): UtilHttp<D & {
117
134
  method: "GET";
118
135
  }, SendProc<[]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
119
136
  /**有查询参数获取json的get预设 */
120
- queryJson(): UtilCom<D & {
137
+ queryJson(): UtilHttp<D & {
121
138
  method: "GET";
122
139
  }, SendProc<[QueryRequestData]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
123
140
  /**收发皆为json的https-post预设 */
124
- static httpsPostJson(): UtilCom<{
141
+ static httpsPostJson(): UtilHttp<{
125
142
  readonly protocol: "https:";
126
143
  } & {
127
144
  method: "POST";
@@ -131,7 +148,7 @@ export declare class UtilCom<D extends Partial<RequestOption> & Required<Pick<Re
131
148
  };
132
149
  }, SendProc<[JToken]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
133
150
  /**收发皆为json的http-post预设 */
134
- static httpPostJson(): UtilCom<{
151
+ static httpPostJson(): UtilHttp<{
135
152
  readonly protocol: "http:";
136
153
  } & {
137
154
  method: "POST";
@@ -141,87 +158,117 @@ export declare class UtilCom<D extends Partial<RequestOption> & Required<Pick<Re
141
158
  };
142
159
  }, SendProc<[JToken]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
143
160
  /**无查询参数获取json的https-get预设 */
144
- static httpsGetJson(): UtilCom<{
161
+ static httpsGetJson(): UtilHttp<{
145
162
  readonly protocol: "https:";
146
163
  } & {
147
164
  method: "GET";
148
165
  }, SendProc<[]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
149
166
  /**有查询参数获取json的https-get预设 */
150
- static httpsQueryJson(): UtilCom<{
167
+ static httpsQueryJson(): UtilHttp<{
151
168
  readonly protocol: "http:";
152
169
  } & {
153
170
  method: "GET";
154
171
  }, SendProc<[QueryRequestData]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
155
172
  /**无查询参数获取json的http-get预设 */
156
- static httpGetJson(): UtilCom<{
173
+ static httpGetJson(): UtilHttp<{
157
174
  readonly protocol: "http:";
158
175
  } & {
159
176
  method: "GET";
160
177
  }, SendProc<[]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
161
178
  /**有查询参数获取json的http-get预设 */
162
- static httpQueryJson(): UtilCom<{
179
+ static httpQueryJson(): UtilHttp<{
163
180
  readonly protocol: "http:";
164
181
  } & {
165
182
  method: "GET";
166
183
  }, SendProc<[QueryRequestData]>, AcceptProc<string, RequestResult<JToken> | undefined>>;
167
184
  /**预设的接收数据类型*/
168
185
  accept<T extends AcceptType>(t: T): {
169
- readonly json: UtilCom<D, S, AcceptProc<string, RequestResult<JToken> | undefined>>;
170
- readonly string: UtilCom<D, S, AcceptProc<string, RequestResult<string> | undefined>>;
171
- readonly none: UtilCom<D, S, AcceptProc<undefined, undefined>>;
186
+ readonly json: UtilHttp<D, S, AcceptProc<string, RequestResult<JToken> | undefined>>;
187
+ readonly string: UtilHttp<D, S, AcceptProc<string, RequestResult<string> | undefined>>;
188
+ readonly none: UtilHttp<D, S, AcceptProc<undefined, undefined>>;
172
189
  }[T];
173
- acceptJson(): UtilCom<D, S, AcceptProc<string, RequestResult<JToken> | undefined>>;
174
- acceptString(): UtilCom<D, S, typeof AcceptStringProc>;
175
- acceptNone(): UtilCom<D, S, typeof AcceptNoneProc>;
190
+ acceptJson(): UtilHttp<D, S, AcceptProc<string, RequestResult<JToken> | undefined>>;
191
+ acceptString(): UtilHttp<D, S, typeof AcceptStringProc>;
192
+ acceptNone(): UtilHttp<D, S, typeof AcceptNoneProc>;
176
193
  /**自定的接收数据类型*/
177
- acceptRaw<AD, AT>(proc: AcceptProc<AD, AT>): UtilCom<D, S, typeof proc>;
178
- /**预设的发送数据类型*/
194
+ acceptRaw<AD, AT>(proc: AcceptProc<AD, AT>): UtilHttp<D, S, typeof proc>;
195
+ /**预设的发送数据类型 */
179
196
  send<T extends SendType>(t: T): {
180
- readonly json: UtilCom<D & {
197
+ readonly json: UtilHttp<D & {
181
198
  headers: {
182
199
  "Content-Type": "application/json";
183
200
  };
184
201
  }, SendProc<[JToken]>, A>;
185
- readonly query: UtilCom<D, SendProc<[QueryRequestData]>, A>;
186
- readonly formData: UtilCom<D & {
202
+ readonly query: UtilHttp<D, SendProc<[QueryRequestData]>, A>;
203
+ readonly formData: UtilHttp<D & {
187
204
  headers: {
188
205
  "Content-Type": "multipart/form-data";
189
206
  };
190
207
  }, SendProc<[FormData]>, A>;
191
- readonly none: UtilCom<D, SendProc<[]>, A>;
208
+ readonly form: UtilHttp<D & {
209
+ headers: {
210
+ "Content-Type": "application/x-www-form-urlencoded";
211
+ };
212
+ }, SendProc<[QueryRequestData]>, A>;
213
+ readonly file: UtilHttp<D & {
214
+ headers: {
215
+ "Content-Type": "multipart/form-data";
216
+ };
217
+ }, SendProc<[string, (string | undefined)?]>, A>;
218
+ readonly none: UtilHttp<D, SendProc<[]>, A>;
192
219
  }[T];
193
- /**利用 req.write 发送一段json */
194
- sendJson(): UtilCom<D & {
220
+ /**发送json
221
+ * 请求参数为 (token:JToken)
222
+ */
223
+ sendJson(): UtilHttp<D & {
195
224
  headers: {
196
225
  "Content-Type": "application/json";
197
226
  };
198
227
  }, SendProc<[JToken]>, A>;
199
- /**利用 appendQuery 直接将数据附加在path上发送请求 */
200
- sendQuery(): UtilCom<D, SendProc<[QueryRequestData]>, A>;
201
- sendFormData(): UtilCom<D & {
228
+ /**利用 appendQuery 直接将数据附加在path上发送请求
229
+ * 请求参数为 (form:QueryRequestData)
230
+ */
231
+ sendQuery(): UtilHttp<D, SendProc<[QueryRequestData]>, A>;
232
+ /**发送表单数据
233
+ * 请求参数为 (formData: FormData)
234
+ */
235
+ sendFormData(): UtilHttp<D & {
202
236
  headers: {
203
237
  "Content-Type": "multipart/form-data";
204
238
  };
205
239
  }, SendProc<[FormData]>, A>;
206
- sendNone(): UtilCom<D, typeof SendNoneProc, A>;
207
- /**自定的发送数据类型*/
208
- sendRaw<T extends any[]>(proc: SendProc<T>): UtilCom<D, typeof proc, A>;
240
+ /**发送表单
241
+ * 请求参数为 (form:QueryRequestData)
242
+ */
243
+ sendForm(): UtilHttp<D & {
244
+ headers: {
245
+ "Content-Type": "application/x-www-form-urlencoded";
246
+ };
247
+ }, SendProc<[QueryRequestData]>, A>;
248
+ /**发送文件
249
+ * 请求参数为 (filepath:string, filename?: string)
250
+ */
251
+ sendFile(): UtilHttp<D & {
252
+ headers: {
253
+ "Content-Type": "multipart/form-data";
254
+ };
255
+ }, SendProc<[string, (string | undefined)?]>, A>;
256
+ sendNone(): UtilHttp<D, typeof SendNoneProc, A>;
257
+ /**自定的发送数据类型 */
258
+ sendRaw<T extends any[]>(proc: SendProc<T>): UtilHttp<D, typeof proc, A>;
209
259
  /**发送请求
210
- * @param option - 网络请求选项
211
260
  * @param datas - 数据对象
212
261
  */
213
- once(option: PartialOption<RequestOption, D>, ...datas: SendParams<S>): Promise<ParseResult<A>>;
262
+ once(...datas: {} extends RequiredOnly<PartialOption<RequestOption, D>> ? SendParams<S> : [Error & "RequestOption不完整, 请使用 finalize 完成必要项"]): Promise<ParseResult<A>>;
214
263
  /**重复发送网络请求
215
- * @param option - 网络请求选项
216
264
  * @param verify - 有效性验证函数
217
265
  * @param retries - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
218
266
  * @param datas - 数据对象
219
267
  */
220
268
  retry(opt: {
221
- option: PartialOption<RequestOption, D>;
222
269
  verify?: StatusVerifyFn<ParseResult<A>>;
223
270
  retries?: PromiseRetries;
224
- }, ...datas: SendParams<S>): Promise<import("@zwa73/js-utils").PromiseRetryResult<ParseResult<A>>>;
271
+ }, ...datas: {} extends RequiredOnly<PartialOption<RequestOption, D>> ? SendParams<S> : [Error & "RequestOption不完整, 请使用 finalize 完成必要项"]): Promise<import("@zwa73/js-utils").PromiseRetryResult<ParseResult<A>>>;
225
272
  /**发送网络请求
226
273
  * @param option - 网络请求选项
227
274
  * @param proc - 请求处理函数 需调用req.end()
@@ -3,15 +3,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.UtilCom = void 0;
6
+ exports.UtilHttp = void 0;
7
7
  const http_1 = __importDefault(require("http"));
8
8
  const https_1 = __importDefault(require("https"));
9
+ const url_1 = require("url");
9
10
  const UtilLogger_1 = require("./UtilLogger");
10
11
  const UtilFunctions_1 = require("./UtilFunctions");
11
12
  const querystring_1 = __importDefault(require("querystring"));
13
+ const form_data_1 = __importDefault(require("form-data"));
12
14
  const http_proxy_agent_1 = __importDefault(require("http-proxy-agent"));
13
15
  const https_proxy_agent_1 = __importDefault(require("https-proxy-agent"));
14
16
  const js_utils_1 = require("@zwa73/js-utils");
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const pathe_1 = __importDefault(require("pathe"));
15
19
  const AcceptTypeList = ["json", "string"];
16
20
  const SendTypeList = ["json", "query", "formData", "none"];
17
21
  const SendNoneProc = {
@@ -27,8 +31,8 @@ const AcceptNoneProc = {
27
31
  reduce: () => undefined,
28
32
  parse: () => undefined
29
33
  };
30
- /**网络请求工具 */
31
- class UtilCom {
34
+ /**http请求工具 */
35
+ class UtilHttp {
32
36
  _data;
33
37
  _send;
34
38
  _accept;
@@ -40,11 +44,23 @@ class UtilCom {
40
44
  //#region 流式创建
41
45
  /**设为https请求 */
42
46
  static https() {
43
- return new UtilCom({ protocol: 'https:' }, SendNoneProc, AcceptStringProc);
47
+ return new UtilHttp({ protocol: 'https:' }, SendNoneProc, AcceptStringProc);
44
48
  }
45
49
  /**设为http请求 */
46
50
  static http() {
47
- return new UtilCom({ protocol: 'http:' }, SendNoneProc, AcceptStringProc);
51
+ return new UtilHttp({ protocol: 'http:' }, SendNoneProc, AcceptStringProc);
52
+ }
53
+ /**从url创建 */
54
+ static url(urlStr) {
55
+ const { protocol, hostname, port, pathname } = new url_1.URL(urlStr);
56
+ if (!['http:', 'https:'].includes(protocol))
57
+ UtilFunctions_1.UtilFunc.throwError(`url协议错误: ${urlStr}`);
58
+ const req = new UtilHttp({ protocol: protocol }, SendNoneProc, AcceptStringProc);
59
+ return req.option({
60
+ hostname,
61
+ path: pathname,
62
+ port: port ? parseInt(port) : undefined,
63
+ });
48
64
  }
49
65
  /**设为get方式的请求 */
50
66
  get() {
@@ -57,12 +73,21 @@ class UtilCom {
57
73
  return this;
58
74
  }
59
75
  /**补充参数
76
+ * 不会检查必要参数完整性
60
77
  * 将会替换对应字段, 修改headers请用header函数
61
78
  */
62
79
  option(option) {
63
80
  this._data = { ...this._data, ...option };
64
81
  return this;
65
82
  }
83
+ /**完成参数
84
+ * 会检查必要参数完整性
85
+ * 将会替换对应字段, 修改headers请用header函数
86
+ */
87
+ finalize(option) {
88
+ this._data = { ...this._data, ...option };
89
+ return this;
90
+ }
66
91
  /**补充header */
67
92
  header(headers) {
68
93
  this._data.headers = {
@@ -81,9 +106,13 @@ class UtilCom {
81
106
  }
82
107
  /**添加一段query */
83
108
  query(data) {
84
- this._data.path = UtilCom.buildQuery(this._data.path ?? '', data);
109
+ this._data.path = UtilHttp.buildQuery(this._data.path ?? '', data);
85
110
  return this;
86
111
  }
112
+ /**克隆 */
113
+ clone() {
114
+ return new UtilHttp({ ...this._data }, this._send, this._accept);
115
+ }
87
116
  //#endregion
88
117
  //#region 快速预设
89
118
  /**收发皆为json的预设 */
@@ -104,27 +133,27 @@ class UtilCom {
104
133
  }
105
134
  /**收发皆为json的https-post预设 */
106
135
  static httpsPostJson() {
107
- return UtilCom.https().postJson();
136
+ return UtilHttp.https().postJson();
108
137
  }
109
138
  /**收发皆为json的http-post预设 */
110
139
  static httpPostJson() {
111
- return UtilCom.http().postJson();
140
+ return UtilHttp.http().postJson();
112
141
  }
113
142
  /**无查询参数获取json的https-get预设 */
114
143
  static httpsGetJson() {
115
- return UtilCom.https().getJson();
144
+ return UtilHttp.https().getJson();
116
145
  }
117
146
  /**有查询参数获取json的https-get预设 */
118
147
  static httpsQueryJson() {
119
- return UtilCom.http().queryJson();
148
+ return UtilHttp.http().queryJson();
120
149
  }
121
150
  /**无查询参数获取json的http-get预设 */
122
151
  static httpGetJson() {
123
- return UtilCom.http().getJson();
152
+ return UtilHttp.http().getJson();
124
153
  }
125
154
  /**有查询参数获取json的http-get预设 */
126
155
  static httpQueryJson() {
127
- return UtilCom.http().queryJson();
156
+ return UtilHttp.http().queryJson();
128
157
  }
129
158
  //#endregion
130
159
  //#region 接收数据类型
@@ -180,27 +209,32 @@ class UtilCom {
180
209
  }
181
210
  //#endregion
182
211
  //#region 发送数据类型
183
- /**预设的发送数据类型*/
212
+ /**预设的发送数据类型 */
184
213
  send(t) {
185
214
  const map = {
186
215
  'json': this.sendJson(),
187
216
  'query': this.sendQuery(),
188
217
  'formData': this.sendFormData(),
218
+ 'form': this.sendForm(),
219
+ 'file': this.sendFile(),
189
220
  'none': this.sendNone(),
190
221
  };
191
222
  return map[t];
192
223
  }
193
- /**利用 req.write 发送一段json */
224
+ /**发送json
225
+ * 请求参数为 (token:JToken)
226
+ */
194
227
  sendJson() {
195
228
  const proc = {
196
- proc: (opt, reqData) => {
229
+ proc: (opt, token) => {
197
230
  const { method } = opt;
198
231
  const isPost = (method == "POST");
232
+ const data = JSON.stringify(token);
199
233
  this._data.headers ??= {};
200
- this._data.headers['Content-Length'] = Buffer.byteLength(JSON.stringify(reqData));
234
+ this._data.headers['Content-Length'] = Buffer.byteLength(data);
201
235
  const procReq = (req) => {
202
236
  if (isPost)
203
- req.write(JSON.stringify(reqData));
237
+ req.write(data);
204
238
  req.end();
205
239
  };
206
240
  return procReq;
@@ -211,11 +245,13 @@ class UtilCom {
211
245
  this._data.headers['Content-Type'] = 'application/json';
212
246
  return this;
213
247
  }
214
- /**利用 appendQuery 直接将数据附加在path上发送请求 */
248
+ /**利用 appendQuery 直接将数据附加在path上发送请求
249
+ * 请求参数为 (form:QueryRequestData)
250
+ */
215
251
  sendQuery() {
216
252
  const proc = {
217
- proc: (opt, reqData) => {
218
- opt.path = UtilCom.buildQuery(opt.path ?? '', reqData);
253
+ proc: (opt, form) => {
254
+ opt.path = UtilHttp.buildQuery(opt.path ?? '', form);
219
255
  const procReq = (req) => void req.end();
220
256
  return procReq;
221
257
  }
@@ -223,15 +259,62 @@ class UtilCom {
223
259
  this._send = proc;
224
260
  return this;
225
261
  }
262
+ /**发送表单数据
263
+ * 请求参数为 (formData: FormData)
264
+ */
226
265
  sendFormData() {
227
266
  const proc = {
228
267
  proc: (opt, formData) => {
229
268
  opt.headers = formData.getHeaders();
230
269
  const procReq = (req) => {
231
270
  formData.pipe(req);
271
+ };
272
+ return procReq;
273
+ },
274
+ };
275
+ this._send = proc;
276
+ this._data.headers ??= {};
277
+ this._data.headers['Content-Type'] = 'multipart/form-data';
278
+ return this;
279
+ }
280
+ /**发送表单
281
+ * 请求参数为 (form:QueryRequestData)
282
+ */
283
+ sendForm() {
284
+ const proc = {
285
+ proc: (opt, form) => {
286
+ const { method } = opt;
287
+ const isPost = (method == "POST");
288
+ const data = querystring_1.default.stringify(form);
289
+ this._data.headers ??= {};
290
+ this._data.headers['Content-Length'] = Buffer.byteLength(data);
291
+ const procReq = (req) => {
292
+ if (isPost)
293
+ req.write(data);
232
294
  req.end();
233
295
  };
234
296
  return procReq;
297
+ }
298
+ };
299
+ this._send = proc;
300
+ this._data.headers ??= {};
301
+ this._data.headers['Content-Type'] = 'application/x-www-form-urlencoded';
302
+ return this;
303
+ }
304
+ /**发送文件
305
+ * 请求参数为 (filepath:string, filename?: string)
306
+ */
307
+ sendFile() {
308
+ const proc = {
309
+ proc: (opt, filepath, filename) => {
310
+ const formData = new form_data_1.default();
311
+ filename = filename ?? pathe_1.default.basename(filepath);
312
+ formData.append(filename, fs_1.default.createReadStream(filepath));
313
+ opt.headers = formData.getHeaders();
314
+ const procReq = (req) => {
315
+ formData.pipe(req);
316
+ };
317
+ return procReq;
235
318
  },
236
319
  };
237
320
  this._send = proc;
@@ -243,34 +326,32 @@ class UtilCom {
243
326
  this._send = SendNoneProc;
244
327
  return this;
245
328
  }
246
- /**自定的发送数据类型*/
329
+ /**自定的发送数据类型 */
247
330
  sendRaw(proc) {
248
331
  this._send = proc;
249
332
  return this;
250
333
  }
251
334
  //#endregion
252
335
  /**发送请求
253
- * @param option - 网络请求选项
254
336
  * @param datas - 数据对象
255
337
  */
256
- async once(option, ...datas) {
257
- const fullopt = Object.assign({}, this._data, option);
338
+ async once(...datas) {
339
+ const fullopt = this._data;
258
340
  const proc = await this._send.proc(fullopt, ...datas);
259
341
  const { reduce, init, parse } = this._accept;
260
- const res = await UtilCom.request(fullopt, proc, reduce, init);
342
+ const res = await UtilHttp.request(fullopt, proc, reduce, init);
261
343
  return parse(res);
262
344
  }
263
345
  /**重复发送网络请求
264
- * @param option - 网络请求选项
265
346
  * @param verify - 有效性验证函数
266
347
  * @param retries - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
267
348
  * @param datas - 数据对象
268
349
  */
269
350
  async retry(opt, ...datas) {
270
- let { option, retries, verify } = opt;
351
+ let { retries, verify } = opt;
271
352
  retries ??= {};
272
353
  retries.tryDelay = retries.tryDelay ?? 1000;
273
- const procFn = async () => this.once(option, ...datas);
354
+ const procFn = async () => this.once(...datas);
274
355
  return UtilFunctions_1.UtilFunc.retryPromise(procFn, verify, retries);
275
356
  }
276
357
  /**发送网络请求
@@ -359,14 +440,43 @@ class UtilCom {
359
440
  return base;
360
441
  }
361
442
  }
362
- exports.UtilCom = UtilCom;
443
+ exports.UtilHttp = UtilHttp;
363
444
  if (false)
364
445
  void ((async () => {
365
- const t = await UtilCom.https().postJson()
366
- .once({
367
- hostname: 'httpbin.org',
368
- path: '/post',
369
- timeout: 10000
370
- }, { test: 1 });
371
- console.log(t);
446
+ const tool = UtilHttp
447
+ .url('https://httpbin.org/post')
448
+ .post()
449
+ .finalize({ timeout: 10000 });
450
+ //json
451
+ const sj = await tool.clone()
452
+ .sendJson()
453
+ .acceptJson()
454
+ .once({ test: 1 });
455
+ console.log(sj);
456
+ //form
457
+ const sf = await tool.clone()
458
+ .sendForm()
459
+ .acceptJson()
460
+ .once({ test: 1 });
461
+ console.log(sf);
462
+ //query
463
+ const sq = await tool.clone()
464
+ .sendQuery()
465
+ .acceptJson()
466
+ .once({ test: 1 });
467
+ console.log(sq);
468
+ const filepath = pathe_1.default.join(__dirname, '..', 'input.wav');
469
+ //formData
470
+ //const form = new FormData();
471
+ //form.append('name', 'input.wav');
472
+ //form.append('file', fs.createReadStream(path.join(__dirname,'..','input.wav')));
473
+ //const sfd = await tool.clone()
474
+ // .sendFormData()
475
+ // .acceptJson()
476
+ // .once(form);
477
+ const sfile = await tool.clone()
478
+ .sendFile()
479
+ .acceptJson()
480
+ .once(filepath);
481
+ console.log(sfile);
372
482
  })());
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export * from './UtilFunctions';
2
2
  export * from './UtilInterfaces';
3
3
  export * from './UtilSymbol';
4
4
  export * from './UtilClass';
5
- export * from './UtilCom';
5
+ export * from './UtilHttp';
6
6
  export * from './UtilCodecs';
7
7
  export * from './UtilDecorators';
8
8
  export * from './UtilFileTools';
package/dist/index.js CHANGED
@@ -35,7 +35,7 @@ __exportStar(require("./UtilFunctions"), exports);
35
35
  __exportStar(require("./UtilInterfaces"), exports);
36
36
  __exportStar(require("./UtilSymbol"), exports);
37
37
  __exportStar(require("./UtilClass"), exports);
38
- __exportStar(require("./UtilCom"), exports);
38
+ __exportStar(require("./UtilHttp"), exports);
39
39
  __exportStar(require("./UtilCodecs"), exports);
40
40
  __exportStar(require("./UtilDecorators"), exports);
41
41
  __exportStar(require("./UtilFileTools"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zwa73/utils",
3
- "version": "1.0.218",
3
+ "version": "1.0.220",
4
4
  "description": "my utils",
5
5
  "main": "index.js",
6
6
  "scripts": {