@zwa73/utils 1.0.201 → 1.0.203

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,345 +0,0 @@
1
- import { AnyString,JToken, MPromise, StatusVerifyFn } from "@/src/UtilInterfaces";
2
- import https from 'https';
3
- import http from 'http';
4
- import { SLogger } from "@/src/UtilLogger";
5
- import { RepeatPromiseOpt, UtilFunc } from "@/src/UtilFunctions";
6
- import qs from "querystring";
7
-
8
- /**网络请求返回值 */
9
- export type ComResp<T> = {
10
- /**响应头 */
11
- headers: http.IncomingHttpHeaders;
12
- /**响应状态码 */
13
- statusCode?: number;
14
- /**响应数据 */
15
- data: T;
16
- }
17
-
18
- /**网络请求选项 */
19
- export type ComRequestOption = {
20
- /**请求协议 */
21
- protocol: 'http:'|'https:';
22
- /**超时时间/毫秒 最小为10_000 默认无限 */
23
- timeout?:number;
24
- /**请求域名 */
25
- hostname: string;
26
- /**请求路径 */
27
- path?: string;
28
- /**请求方式 post 为 */
29
- method: 'POST'|'GET';
30
- /**端口 */
31
- port?:number;
32
- /**请求头 */
33
- headers?: {
34
- /**内容类型 */
35
- 'Content-Type'?: 'application/json'|AnyString;
36
- /**内容长度 一般无需填写 应为buffer长度而非字符串长度 */
37
- 'Content-Length'?: number;
38
- };
39
- }&http.RequestOptions;
40
-
41
- /**get请求所允许的数据 */
42
- export type GetReqData = NodeJS.Dict<
43
- | string
44
- | number
45
- | boolean
46
- | readonly string[]
47
- | readonly number[]
48
- | readonly boolean[]
49
- | null
50
- >;
51
-
52
- /**请求处理函数 需调用req.end() */
53
- export type ProcReqFn = ((req:http.ClientRequest)=>MPromise<void>);
54
- /**数据处理函数 */
55
- export type ReduceDataFn<T> = (acc:T,data:string)=>MPromise<T>;
56
-
57
- /**网络工具 */
58
- export namespace UtilCom{
59
-
60
-
61
- /**网络请求
62
- * @param comReqOpt - 网络请求选项
63
- * @param procReq - 请求处理函数 需调用req.end()
64
- * @param reduceData - 数据处理函数
65
- * @param initData - 初始数据
66
- */
67
- export async function comReq<T>(
68
- comReqOpt:ComRequestOption,
69
- procReq:ProcReqFn,
70
- reduceData:ReduceDataFn<T>,
71
- initData:T,
72
- ){
73
- const {protocol,timeout,...baseReqOpt} = comReqOpt;
74
-
75
- const hasTimeLimit = (timeout ? timeout>=10_000 : false );
76
-
77
- const flagName = `${comReq.name}.${protocol}${baseReqOpt.method}`;
78
-
79
- return new Promise<ComResp<T>|undefined>(async (resolve, rejecte)=>{
80
- const resFunc = (res:http.IncomingMessage)=>{
81
- try{
82
- //请求超时
83
- if(hasTimeLimit){
84
- res.setTimeout(timeout!, ()=>{
85
- SLogger.warn(`${flagName} 接收反馈超时: ${timeout} ms`);
86
- resolve(undefined);
87
- });
88
- }
89
-
90
- let mergedata:T = initData;
91
- res.setEncoding('utf8');
92
- res.on('data', async chunk => mergedata=await reduceData(mergedata,chunk));
93
-
94
- res.on('error',(e)=>{
95
- SLogger.warn(`${flagName} 接收反馈错误:${e}`);
96
- resolve(undefined);
97
- });
98
-
99
- res.on('end',()=>{
100
- resolve({
101
- headers: res.headers,
102
- statusCode: res.statusCode,
103
- data: mergedata,
104
- });
105
- });
106
- }catch(err){
107
- SLogger.warn(`${flagName} 未知错误:${err}`);
108
- resolve(undefined);
109
- return;
110
- }
111
- };
112
- //路由 http/https
113
- const req:http.ClientRequest= protocol=="https:"
114
- ? https.request(baseReqOpt as http.RequestOptions, resFunc)
115
- : http.request(baseReqOpt as http.RequestOptions, resFunc);
116
-
117
- //请求超时
118
- if(hasTimeLimit){
119
- req.setTimeout(timeout!, ()=>{
120
- SLogger.warn(`${flagName} 发送请求超时: ${timeout} ms`);
121
- req.destroy();
122
- });
123
- //req.on('timeout', ()=>{
124
- // SLogger.warn(`${flagName} 发送请求超时(timeout): ${timeLimit} ms`);
125
- // req.destroy();
126
- //});
127
- }
128
-
129
- req.on('error', (e)=>{
130
- SLogger.warn(`${flagName} 发送请求错误:${e}`);
131
- resolve(undefined);
132
- });
133
-
134
- await procReq(req);
135
- });
136
- }
137
-
138
- /**发送json的网络请求
139
- * @param comReqOpt - 网络请求选项
140
- * @param reqData - 数据对象
141
- * @returns 结果 undefined 为未能成功接收
142
- */
143
- async function jsonReq<T extends ComRequestOption>(
144
- comReqOpt:T,
145
- reqData?:T['method'] extends "POST" ? JToken :GetReqData
146
- ){
147
- const {method} = comReqOpt;
148
- const isPost = (method=="POST");
149
-
150
- if (!isPost && reqData != undefined) {
151
- const queryString = qs.stringify(reqData as GetReqData);
152
- if (queryString) {
153
- // 检查当前路径是否已经包含问号
154
- const separator = comReqOpt?.path?.includes('?') ? '&' : '?';
155
- comReqOpt.path += separator + queryString;
156
- }
157
- }
158
-
159
- const procReq = (req:http.ClientRequest)=>{
160
- if(isPost) req.write(JSON.stringify(reqData));
161
- req.end();
162
- }
163
-
164
- const reduceData = (acc:string,data:string)=>acc+data;
165
- const result = await comReq(comReqOpt,procReq,reduceData,"");
166
- if(result==undefined) return undefined;
167
- const {data,...rest} = result;
168
-
169
- if(data.trim()==""){
170
- SLogger.warn(`${jsonReq.name} 接收反馈错误: 原始字符串为空`);
171
- return {...result,raw:"",data:null};
172
- }
173
-
174
- try{
175
- const obj = JSON.parse(data.trim()) as JToken;
176
- SLogger.http(`${jsonReq.name} 接受信息:`,UtilFunc.stringifyJToken(obj,{compress:true,space:2}));
177
- return{...rest,data:obj};
178
- }
179
- catch(e){
180
- SLogger.warn(`${jsonReq.name} 接收反馈错误:${e}\n原始字符串:${data}`);
181
- return {...result,raw:data,data:null};
182
- }
183
- }
184
-
185
- /**重复发送json的网络请求
186
- * @async
187
- * @param comReqOpt - 网络请求选项
188
- * @param reqData - 数据对象
189
- * @param verifyFn - 有效性验证函数
190
- * @param repeatOpt - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
191
- * @returns 结果 undefined 为未能成功接收
192
- */
193
- async function repeatJsonComReq<T extends ComRequestOption>(
194
- comReqOpt:T,
195
- reqData?:T['method'] extends "POST" ? JToken :GetReqData,
196
- verifyFn?:StatusVerifyFn<ComResp<JToken>|undefined>,
197
- repeatOpt:RepeatPromiseOpt={},
198
- ){
199
- repeatOpt.tryDelay = repeatOpt.tryDelay??1000;
200
- const procFn = ()=>jsonReq(comReqOpt,reqData);
201
- return UtilFunc.repeatPromise(procFn,verifyFn,repeatOpt);
202
- }
203
-
204
- /**发送一个 https POST 请求并接受数据
205
- * @async
206
- * @param comReqOpt - 请求参数
207
- * @param reqData - 数据对象
208
- * @returns 结果 undefined 为未能成功接收
209
- */
210
- export function httpsPost(comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,reqData?:JToken){
211
- return jsonReq({
212
- ...comReqOpt,
213
- method:"POST",
214
- protocol:"https:",
215
- },reqData);
216
- }
217
-
218
- /**发送一个 http POST 请求并接受数据
219
- * @async
220
- * @param comReqOpt - 请求参数
221
- * @param reqData - 数据对象
222
- * @returns 结果 undefined 为未能成功接收
223
- */
224
- export function httpPost(comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,reqData?:JToken){
225
- return jsonReq({
226
- ...comReqOpt,
227
- method:"POST",
228
- protocol:"http:",
229
- },reqData);
230
- }
231
-
232
- /**发送一个 https GET 请求并接受数据
233
- * @async
234
- * @param comReqOpt - 请求参数
235
- * @param reqData - 数据对象
236
- * @returns 结果 undefined 为未能成功接收
237
- */
238
- export function httpsGet(comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,reqData?:GetReqData){
239
- return jsonReq({
240
- ...comReqOpt,
241
- method:"GET",
242
- protocol:"https:",
243
- },reqData);
244
- }
245
-
246
- /**发送一个 http GET 请求并接受数据
247
- * @async
248
- * @param comReqOpt - 请求参数
249
- * @param reqData - 数据对象
250
- * @returns 结果 undefined 为未能成功接收
251
- */
252
- export function httpGet(comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,reqData?:GetReqData){
253
- return jsonReq({
254
- ...comReqOpt,
255
- method:"GET",
256
- protocol:"http:",
257
- },reqData);
258
- }
259
-
260
-
261
- /**重复一个 https POST请求并接受数据
262
- * @async
263
- * @param comReqOpt - 网络请求选项
264
- * @param reqData - 数据对象
265
- * @param verifyFn - 有效性验证函数
266
- * @param repeatOpt - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
267
- * @returns 结果 undefined 为未能成功接收
268
- */
269
- export function httpsRepeatPost(
270
- comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,
271
- reqData?:JToken,
272
- verifyFn?:StatusVerifyFn<JToken|undefined>,
273
- repeatOpt?:RepeatPromiseOpt
274
- ){
275
- return repeatJsonComReq({
276
- ...comReqOpt,
277
- method:"POST",
278
- protocol:"https:",
279
- },reqData,verifyFn,repeatOpt);
280
- }
281
-
282
- /**重复一个 http POST请求并接受数据
283
- * @async
284
- * @param comReqOpt - 网络请求选项
285
- * @param reqData - 数据对象
286
- * @param verifyFn - 有效性验证函数
287
- * @param repeatOpt - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
288
- * @returns 结果 undefined 为未能成功接收
289
- */
290
- export function httpRepeatPost(
291
- comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,
292
- reqData?:JToken,
293
- verifyFn?:StatusVerifyFn<JToken|undefined>,
294
- repeatOpt?:RepeatPromiseOpt
295
- ){
296
- return repeatJsonComReq({
297
- ...comReqOpt,
298
- method:"POST",
299
- protocol:"http:",
300
- },reqData,verifyFn,repeatOpt);
301
- }
302
-
303
- /**重复一个 https GET 请求并接受数据
304
- * @async
305
- * @param comReqOpt - 网络请求选项
306
- * @param reqData - 数据对象
307
- * @param verifyFn - 有效性验证函数
308
- * @param repeatOpt - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
309
- * @returns 结果 undefined 为未能成功接收
310
- */
311
- export function httpsRepeatGet(
312
- comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,
313
- reqData?:GetReqData,
314
- verifyFn?:StatusVerifyFn<JToken|undefined>,
315
- repeatOpt?:RepeatPromiseOpt
316
- ){
317
- return repeatJsonComReq({
318
- ...comReqOpt,
319
- method:"GET",
320
- protocol:"https:",
321
- },reqData,verifyFn,repeatOpt);
322
- }
323
-
324
- /**重复一个 http GET 请求并接受数据
325
- * @async
326
- * @param comReqOpt - 网络请求选项
327
- * @param reqData - 数据对象
328
- * @param verifyFn - 有效性验证函数
329
- * @param repeatOpt - 重试选项 默认 延迟:1000ms 间隔:180_000ms 重试:3次
330
- * @returns 结果 undefined 为未能成功接收
331
- */
332
- export function httpRepeatGet(
333
- comReqOpt:Omit<ComRequestOption,'protocol'|'method'>,
334
- reqData?:GetReqData,
335
- verifyFn?:StatusVerifyFn<JToken|undefined>,
336
- repeatOpt?:RepeatPromiseOpt
337
- ){
338
- return repeatJsonComReq({
339
- ...comReqOpt,
340
- method:"GET",
341
- protocol:"http:",
342
- },reqData,verifyFn,repeatOpt);
343
- }
344
-
345
- }
@@ -1,223 +0,0 @@
1
- import { UtilFunc } from "./UtilFunctions";
2
- import { NeedInit } from "./UtilInterfaces";
3
- import { SLogger } from "./UtilLogger";
4
-
5
- type TDTg<T> =
6
- (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<T>)=>
7
- TypedPropertyDescriptor<T>;
8
- type DTg = (target:Object, propertyKey:string, descriptor:PropertyDescriptor)=>
9
- PropertyDescriptor;
10
-
11
- /**用于打印方法运行时间
12
- * @param flag - 时间标签
13
- * @param suffixUID - 是否尾随uid
14
- */
15
- export function LogTime(flag:string,suffixUID?:boolean):DTg{
16
- return function (target, propertyKey, descriptor){
17
- const originalMethod = descriptor.value;
18
- descriptor.value = function(...args:any[]){
19
- const uid = suffixUID ? UtilFunc.genUUID() : "";
20
- SLogger.time(flag+uid);
21
- let result = originalMethod.apply(this, args);
22
- SLogger.timeEnd(flag+uid);
23
- return result;
24
- }
25
- return descriptor;
26
- }
27
- }
28
- /**用于打印异步方法运行时间
29
- * @param flag - 时间标签
30
- * @param suffixUID - 是否尾随uid
31
- */
32
- export function LogTimeAsync(flag:string,suffixUID?:boolean):DTg{
33
- return function (target, propertyKey, descriptor){
34
- const originalMethod = descriptor.value;
35
- descriptor.value = async function(...args:any[]){
36
- const uid = suffixUID ? UtilFunc.genUUID() : "";
37
- SLogger.time(flag+uid);
38
- let result = await originalMethod.apply(this, args);
39
- SLogger.timeEnd(flag+uid);
40
- return result;
41
- }
42
- return descriptor;
43
- }
44
- }
45
-
46
- /**用于打印方法的调用 */
47
- export function LogCall():DTg{
48
- return function (target, propertyKey, descriptor){
49
- const originalMethod = descriptor.value;
50
- descriptor.value = function(...args:any[]){
51
- let result = originalMethod.apply(this, args);
52
- SLogger.info(`调用函数: ${propertyKey}(${args}) => ${result}`);
53
- return result;
54
- }
55
- return descriptor;
56
- }
57
- }
58
-
59
- /**用于打印异步方法的调用 */
60
- export function LogCallAsync():DTg{
61
- return function (target, propertyKey, descriptor){
62
- const originalMethod = descriptor.value;
63
- descriptor.value = async function(...args:any[]){
64
- let result = await originalMethod.apply(this, args);
65
- SLogger.info(`调用函数: ${propertyKey}(${args}) => ${result}`);
66
- return result;
67
- }
68
- return descriptor;
69
- }
70
- }
71
-
72
- /**用于打印方法的调用 */
73
- export function LogErr():DTg{
74
- return function (target, propertyKey, descriptor){
75
- const originalMethod = descriptor.value;
76
- descriptor.value = function(...args:any[]){
77
- try {
78
- const result = originalMethod.apply(this, args);
79
- return result;
80
- } catch(err) {
81
- UtilFunc.throwError(`函数出现错误: ${propertyKey}(${args}): ${err}`,'warn');
82
- }
83
- }
84
- return descriptor;
85
- }
86
- }
87
-
88
- /**用于打印异步方法的调用 */
89
- export function LogErrAsync():DTg{
90
- return function (target, propertyKey, descriptor){
91
- const originalMethod = descriptor.value;
92
- descriptor.value = async function(...args:any[]){
93
- try {
94
- const result = await originalMethod.apply(this, args);
95
- return result;
96
- } catch(err) {
97
- UtilFunc.throwError(`函数出现错误: ${propertyKey}(${args}): ${err}`,'warn');
98
- }
99
- }
100
- return descriptor;
101
- }
102
- }
103
-
104
- /**try-finally包装 */
105
- export function Defer<T extends (...args:any)=>any>
106
- (deferLogic:(...args:Parameters<T>)=>any):TDTg<T> {
107
- return function(target, propertyKey, descriptor) {
108
- const originalMethod = descriptor.value!;
109
- (descriptor as any).value = function (...args:any) {
110
- try {
111
- const result = originalMethod.apply(this, args);
112
- return result;
113
- } finally {
114
- deferLogic(...args);
115
- }
116
- };
117
- return descriptor;
118
- };
119
- }
120
- /**异步的try-finally包装 */
121
- export function DeferAsync<T extends (...args:any)=>Promise<any>>
122
- (deferLogic:(...args:Parameters<T>)=>any|Promise<any>):TDTg<T> {
123
- return function(target, propertyKey, descriptor) {
124
- const originalMethod = descriptor.value!;
125
- (descriptor as any).value = async function (...args:any) {
126
- try {
127
- const result = await originalMethod.apply(this, args);
128
- await deferLogic(...args);
129
- return result;
130
- } finally {
131
- await deferLogic(...args);
132
- }
133
- };
134
- return descriptor;
135
- };
136
- }
137
- /**try-catch包装 */
138
- export function Catch<T extends (...args:any)=>any>
139
- (catchLogic:(error: any, ...args:Parameters<T>)=>ReturnType<T>):TDTg<T> {
140
- return function(target, propertyKey, descriptor) {
141
- const originalMethod = descriptor.value!;
142
- (descriptor as any).value = function (...args:any) {
143
- try {
144
- const result = originalMethod.apply(this, args);
145
- return result;
146
- } catch(err) {
147
- //SLogger.warn(`一个函数出现了错误 ${propertyKey}: ${err}`);
148
- return catchLogic(err, ...args);
149
- }
150
- };
151
- return descriptor;
152
- };
153
- }
154
- /**异步的try-catch包装 */
155
- export function CatchAsync<T extends (...args:any)=>Promise<any>>
156
- (catchLogic:(error: any, ...args:Parameters<T>)=>ReturnType<T>):TDTg<T> {
157
- return function(target, propertyKey, descriptor) {
158
- const originalMethod = descriptor.value!;
159
- (descriptor as any).value = async function (...args:any) {
160
- try {
161
- const result = await originalMethod.apply(this, args);
162
- return result;
163
- } catch(err) {
164
- //SLogger.warn(`一个函数出现了错误 ${propertyKey}: ${err}`);
165
- return await catchLogic(err, ...args);
166
- }
167
- };
168
- return descriptor;
169
- };
170
- }
171
-
172
- /**等待完成init */
173
- export function AwaitInited<T extends NeedInit>
174
- (target:T, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>) {
175
- const originalMethod = descriptor.value!;
176
-
177
- descriptor.value = async function(this:T,...args: any[]) {
178
- await this.inited;
179
- return await originalMethod.apply(this, args);
180
- };
181
-
182
- return descriptor;
183
- }
184
-
185
-
186
- function AddNumberDecorator(n: number) {
187
- type NumberToNumberFunc = (num: number) => number;
188
- return function(
189
- this:any,
190
- target: Object,
191
- propertyKey: string,
192
- descriptor: TypedPropertyDescriptor<NumberToNumberFunc>
193
- ) {
194
- const originalMethod = descriptor.value!;
195
- descriptor.value = function (num: number) {
196
- const result = originalMethod.apply(this, [num]);
197
- return result + n;
198
- };
199
- return descriptor;
200
- };
201
- }
202
-
203
-
204
-
205
-
206
- class Example {
207
- @AddNumberDecorator(10)
208
- myMethod(num: number): number {
209
- return num;
210
- }
211
- @LogCall()
212
- @Defer((a,b)=>null)
213
- @CatchAsync(async (a,b)=>123)
214
- static async myMethod1(num: number,ss:string) {
215
- return 312;
216
- }
217
- }
218
- //let e = new Example();
219
- //e.myMethod1(1,"");
220
-
221
- //console.log(123);
222
- //let a = new Example();
223
- //a.myMethod(10);//?
@@ -1,29 +0,0 @@
1
- import {regionMacro} from '@zwa73/dev-utils';
2
-
3
- const N = 20;
4
- const R = (n:number)=>n===0?`I`:`R${n}`;
5
- const prefix = (str:string,prefix?:string)=> str.length>0?`${prefix}${str}`:str;
6
- const suffix = (str:string,suffix?:string)=> str.length>0?`${str}${suffix}`:str;
7
-
8
- regionMacro("flow重载",()=>{
9
- const result:string[] = [];
10
- for (let i = 0; i <= N; i++) {
11
- const template = Array.from({length: i+1}, (_, k) => R(k)).join(', ');
12
- const args = suffix(Array.from({length: i}, (_, k) =>
13
- `f${k+1}: CompFunc<${R(k)}, ${R(k+1)}>`
14
- ).join(', '),", ");
15
- result.push(`export function flow<${template}>(${args}...fs: CompFunc<${R(i)}, ${R(i)}>[]): CompFunc<I, ${R(i)}>;`);
16
- }
17
- return result.reverse().join('\n').trim();
18
- });
19
- regionMacro("pipe重载",()=>{
20
- const result:string[] = [];
21
- for (let i = 0; i <= N; i++) {
22
- const template = Array.from({length: i+1}, (_, k) => R(k)).join(', ');
23
- const args = suffix(Array.from({length: i}, (_, k) =>
24
- `f${k+1}: CompFunc<${R(k)}, ${R(k+1)}>`
25
- ).join(', '),", ");
26
- result.push(`export function pipe<${template}>(input: I, ${args}...fs: CompFunc<${R(i)}, ${R(i)}>[]): ${R(i)};`);
27
- }
28
- return result.reverse().join('\n').trim();
29
- });