utils-lib-js 1.0.4 → 1.0.5

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,5 +1,6 @@
1
- import { IRandomNum, IUrlSplit, IUrlJoin, IGetType, types } from "./index.js";
1
+ import { IRandomNum, IUrlSplit, IUrlJoin, IGetType, IGetTypeByList, types } from "./index.js";
2
2
  export declare const randomNum: IRandomNum;
3
3
  export declare const urlSplit: IUrlSplit;
4
4
  export declare const urlJoin: IUrlJoin;
5
5
  export declare const getType: IGetType<types>;
6
+ export declare const getTypeByList: IGetTypeByList;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.getType = exports.urlJoin = exports.urlSplit = exports.randomNum = void 0;
4
+ exports.getTypeByList = exports.getType = exports.urlJoin = exports.urlSplit = exports.randomNum = void 0;
5
5
  var index_js_1 = require("./index.js");
6
6
  var randomNum = function (min, max, bool) {
7
7
  if (bool === void 0) {
@@ -24,7 +24,12 @@ var urlSplit = function (url) {
24
24
  };
25
25
  exports.urlSplit = urlSplit;
26
26
  var urlJoin = function (url, query) {
27
- var params = Object.keys(query).map(function (i) {
27
+ if (query === void 0) {
28
+ query = {};
29
+ }
30
+ var queryObject = Object.keys(query);
31
+ if (queryObject.length === 0) return url;
32
+ var params = queryObject.map(function (i) {
28
33
  return "".concat(i, "=").concat(query[i]);
29
34
  });
30
35
  return "".concat(url).concat(url.includes("?") ? "&" : '?').concat(params.join("&"));
@@ -40,4 +45,12 @@ var getType = function (data) {
40
45
  }
41
46
  return type;
42
47
  };
43
- exports.getType = getType;
48
+ exports.getType = getType;
49
+ var getTypeByList = function (data, whiteList) {
50
+ if (whiteList === void 0) {
51
+ whiteList = [];
52
+ }
53
+ var __type = (0, exports.getType)(data);
54
+ return whiteList.indexOf(__type) > 0;
55
+ };
56
+ exports.getTypeByList = getTypeByList;
@@ -1,4 +1,4 @@
1
- import { IGetValue, ISetValue, IMixIn, ICloneDeep, ICreateObjectVariable, IEnumInversion, IInherit, ICreateObject, IGetInstance, IClassDecorator } from "./index.js";
1
+ import { IGetValue, ISetValue, IMixIn, ICloneDeep, ICreateObjectVariable, IEnumInversion, IInherit, ICreateObject, IGetInstance, IClassDecorator, IStringToJson, IJsonToString } from "./index.js";
2
2
  export declare const getValue: IGetValue;
3
3
  export declare const setValue: ISetValue;
4
4
  export declare const mixIn: IMixIn;
@@ -10,3 +10,5 @@ export declare const createObject: ICreateObject;
10
10
  export declare const inherit: IInherit;
11
11
  export declare const getInstance: IGetInstance;
12
12
  export declare const classDecorator: IClassDecorator;
13
+ export declare const stringToJson: IStringToJson;
14
+ export declare const jsonToString: IJsonToString;
@@ -10,7 +10,7 @@ var __spreadArray = this && this.__spreadArray || function (to, from, pack) {
10
10
  return to.concat(ar || Array.prototype.slice.call(from));
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.classDecorator = exports.getInstance = exports.inherit = exports.createObject = exports.createObjectVariable = exports.cloneDeep = exports.isNotObject = exports.enumInversion = exports.mixIn = exports.setValue = exports.getValue = void 0;
13
+ exports.jsonToString = exports.stringToJson = exports.classDecorator = exports.getInstance = exports.inherit = exports.createObject = exports.createObjectVariable = exports.cloneDeep = exports.isNotObject = exports.enumInversion = exports.mixIn = exports.setValue = exports.getValue = void 0;
14
14
  var index_js_1 = require("./index.js");
15
15
  var getValue = function (object, key, defaultValue) {
16
16
  if (defaultValue === void 0) {
@@ -164,4 +164,22 @@ var classDecorator = function (params) {
164
164
  }
165
165
  };
166
166
  };
167
- exports.classDecorator = classDecorator;
167
+ exports.classDecorator = classDecorator;
168
+ var stringToJson = function (target) {
169
+ if ((0, index_js_1.getType)(target) !== "string") return {};
170
+ try {
171
+ return JSON.parse(target);
172
+ } catch (error) {
173
+ return {};
174
+ }
175
+ };
176
+ exports.stringToJson = stringToJson;
177
+ var jsonToString = function (target) {
178
+ if (!(0, index_js_1.getTypeByList)(target, ["array", "object", "set", "map"])) return "";
179
+ try {
180
+ return JSON.stringify(target);
181
+ } catch (error) {
182
+ return "";
183
+ }
184
+ };
185
+ exports.jsonToString = jsonToString;
@@ -1,15 +1,42 @@
1
- import { IRequest } from "./index.js";
2
- export declare class Request implements IRequest {
1
+ import { IRequest, IRequestBase, IInterceptors } from "./index.js";
2
+ export declare class Interceptors implements IInterceptors {
3
+ private requestSuccess;
4
+ private responseSuccess;
5
+ private error;
6
+ use(type: any, fn: any): this;
7
+ get reqFn(): Function;
8
+ get resFn(): Function;
9
+ get errFn(): Function;
10
+ }
11
+ export declare abstract class RequestBase extends Interceptors implements IRequestBase {
3
12
  origin: string;
4
- constructor();
5
- fixOrigin(origin: any): this;
6
- envDesc(): "Window" | "Node";
7
- ajax(url: any, opts: any): void;
8
- fetch(): Promise<Response>;
9
- http(): void;
13
+ constructor(origin: any);
14
+ abstract fetch(url: any, opts: any): Promise<void>;
15
+ abstract http(url: any, opts: any): Promise<void>;
16
+ chackUrl: (url: any) => any;
17
+ fixOrigin: (fixStr: string) => string;
18
+ envDesc: () => "Window" | "Node";
19
+ requestType: () => (url: any, opts: any) => Promise<void>;
20
+ initFetchParams: (url: any, { method, query, headers, body, timeout, abort, type, ...others }: {
21
+ [x: string]: any;
22
+ method?: string;
23
+ query?: {};
24
+ headers?: {};
25
+ body?: any;
26
+ timeout?: number;
27
+ abort?: AbortController;
28
+ type?: string;
29
+ }) => any;
30
+ getDataByType: (type: any, response: any) => any;
31
+ }
32
+ export declare class Request extends RequestBase implements IRequest {
33
+ request: Function;
34
+ constructor(origin: any);
35
+ fetch: (_url: any, _opts: any) => Promise<void>;
36
+ http: (url: any, opts: any) => Promise<void>;
37
+ GET: (url: any, query: {}, _: any, opts: any) => any;
38
+ POST: (url: any, query: {}, body: any, opts: any) => any;
39
+ PUT: (url: any, query: {}, body: any, opts: any) => any;
40
+ DELETE: (url: any, query: {}, body: any, opts: any) => any;
41
+ OPTION: (url: any, query: {}, body: any, opts: any) => any;
10
42
  }
11
- export declare const GET: () => void;
12
- export declare const POST: () => void;
13
- export declare const PUT: () => void;
14
- export declare const DELETE: () => void;
15
- export declare const OPTION: () => void;
@@ -1,65 +1,221 @@
1
1
  "use strict";
2
2
 
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.OPTION = exports.DELETE = exports.PUT = exports.POST = exports.GET = exports.Request = void 0;
5
- var index_js_1 = require("./index.js");
6
- var Request = function () {
7
- function Request() {}
8
- Request.prototype.fixOrigin = function (origin) {
9
- this.origin = origin;
10
- return this;
3
+ var __extends = this && this.__extends || function () {
4
+ var extendStatics = function (d, b) {
5
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
6
+ d.__proto__ = b;
7
+ } || function (d, b) {
8
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
9
+ };
10
+ return extendStatics(d, b);
11
11
  };
12
- Request.prototype.envDesc = function () {
13
- if (Window) {
14
- return "Window";
12
+ return function (d, b) {
13
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
14
+ extendStatics(d, b);
15
+ function __() {
16
+ this.constructor = d;
15
17
  }
16
- return "Node";
18
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17
19
  };
18
- Request.prototype.ajax = function (url, opts) {
19
- var _a = (0, index_js_1.defer)(),
20
- promise = _a.promise,
21
- resolve = _a.resolve,
22
- reject = _a.reject;
23
- var _b = opts.method,
24
- method = _b === void 0 ? "GET" : _b,
25
- _c = opts.params,
26
- params = _c === void 0 ? {} : _c,
27
- _d = opts.body,
28
- body = _d === void 0 ? {} : _d,
29
- _e = opts.async,
30
- async = _e === void 0 ? true : _e,
31
- _f = opts.timeout,
32
- timeout = _f === void 0 ? 30 * 1000 : _f;
33
- var xhr = new XMLHttpRequest();
34
- switch (method) {
35
- case 'GET':
20
+ }();
21
+ var __assign = this && this.__assign || function () {
22
+ __assign = Object.assign || function (t) {
23
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
24
+ s = arguments[i];
25
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
26
+ }
27
+ return t;
28
+ };
29
+ return __assign.apply(this, arguments);
30
+ };
31
+ var __rest = this && this.__rest || function (s, e) {
32
+ var t = {};
33
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
34
+ if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
35
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
36
+ }
37
+ return t;
38
+ };
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.Request = exports.RequestBase = exports.Interceptors = void 0;
41
+ var index_js_1 = require("./index.js");
42
+ var Interceptors = function () {
43
+ function Interceptors() {}
44
+ Interceptors.prototype.use = function (type, fn) {
45
+ switch (type) {
46
+ case "request":
47
+ this.requestSuccess = fn;
48
+ break;
49
+ case "response":
50
+ this.responseSuccess = fn;
36
51
  break;
37
- default:
52
+ case "error":
53
+ this.error = fn;
38
54
  break;
39
55
  }
40
- xhr.addEventListener('load', function () {
41
- if (xhr.readyState === 4 && xhr.status === 200) {
42
- try {} catch (error) {}
43
- } else {}
44
- });
45
- xhr.open(method, url, async);
46
- xhr.send(body);
47
- xhr.timeout = async && timeout;
48
- };
49
- Request.prototype.fetch = function () {
50
- return fetch("");
56
+ return this;
51
57
  };
52
- Request.prototype.http = function () {};
53
- return Request;
58
+ Object.defineProperty(Interceptors.prototype, "reqFn", {
59
+ get: function () {
60
+ return this.requestSuccess;
61
+ },
62
+ enumerable: false,
63
+ configurable: true
64
+ });
65
+ Object.defineProperty(Interceptors.prototype, "resFn", {
66
+ get: function () {
67
+ return this.responseSuccess;
68
+ },
69
+ enumerable: false,
70
+ configurable: true
71
+ });
72
+ Object.defineProperty(Interceptors.prototype, "errFn", {
73
+ get: function () {
74
+ return this.error;
75
+ },
76
+ enumerable: false,
77
+ configurable: true
78
+ });
79
+ return Interceptors;
54
80
  }();
55
- exports.Request = Request;
56
- var GET = function () {};
57
- exports.GET = GET;
58
- var POST = function () {};
59
- exports.POST = POST;
60
- var PUT = function () {};
61
- exports.PUT = PUT;
62
- var DELETE = function () {};
63
- exports.DELETE = DELETE;
64
- var OPTION = function () {};
65
- exports.OPTION = OPTION;
81
+ exports.Interceptors = Interceptors;
82
+ var RequestBase = function (_super) {
83
+ __extends(RequestBase, _super);
84
+ function RequestBase(origin) {
85
+ var _this = _super.call(this) || this;
86
+ _this.chackUrl = function (url) {
87
+ return url.startsWith('/');
88
+ };
89
+ _this.fixOrigin = function (fixStr) {
90
+ if (_this.chackUrl(fixStr)) return _this.origin + fixStr;
91
+ return fixStr;
92
+ };
93
+ _this.envDesc = function () {
94
+ if (Window) {
95
+ return "Window";
96
+ }
97
+ return "Node";
98
+ };
99
+ _this.requestType = function () {
100
+ switch (_this.envDesc()) {
101
+ case "Window":
102
+ return _this.fetch;
103
+ case "Node":
104
+ return _this.http;
105
+ }
106
+ };
107
+ _this.initFetchParams = function (url, _a) {
108
+ var _b, _c;
109
+ var _d = _a.method,
110
+ method = _d === void 0 ? "GET" : _d,
111
+ _e = _a.query,
112
+ query = _e === void 0 ? {} : _e,
113
+ _f = _a.headers,
114
+ headers = _f === void 0 ? {} : _f,
115
+ _g = _a.body,
116
+ body = _g === void 0 ? null : _g,
117
+ _h = _a.timeout,
118
+ timeout = _h === void 0 ? 30 * 1000 : _h,
119
+ _j = _a.abort,
120
+ abort = _j === void 0 ? new AbortController() : _j,
121
+ _k = _a.type,
122
+ type = _k === void 0 ? "json" : _k,
123
+ others = __rest(_a, ["method", "query", "headers", "body", "timeout", "abort", "type"]);
124
+ url = (0, index_js_1.urlJoin)(_this.fixOrigin(url), query);
125
+ var timer = setTimeout(function () {
126
+ return abort.abort();
127
+ }, timeout);
128
+ var params = __assign({ url: url, method: method, headers: headers, body: method === "GET" ? null : (0, index_js_1.jsonToString)(body), timeout: timeout, timer: timer, signal: abort.signal, type: type }, others);
129
+ return (_c = (_b = _this.reqFn) === null || _b === void 0 ? void 0 : _b.call(_this, params)) !== null && _c !== void 0 ? _c : params;
130
+ };
131
+ _this.getDataByType = function (type, response) {
132
+ switch (type) {
133
+ case "text":
134
+ case "json":
135
+ case "blob":
136
+ case "formData":
137
+ case "arrayBuffer":
138
+ return response[type]();
139
+ default:
140
+ return response['json']();
141
+ }
142
+ };
143
+ _this.origin = origin !== null && origin !== void 0 ? origin : '';
144
+ return _this;
145
+ }
146
+ return RequestBase;
147
+ }(Interceptors);
148
+ exports.RequestBase = RequestBase;
149
+ var Request = function (_super) {
150
+ __extends(Request, _super);
151
+ function Request(origin) {
152
+ var _this = _super.call(this, origin) || this;
153
+ _this.fetch = function (_url, _opts) {
154
+ var _a = (0, index_js_1.defer)(),
155
+ promise = _a.promise,
156
+ resolve = _a.resolve,
157
+ reject = _a.reject;
158
+ var _b = _this.initFetchParams(_url, _opts),
159
+ url = _b.url,
160
+ opts = __rest(_b, ["url"]);
161
+ var signal = opts.signal,
162
+ timer = opts.timer;
163
+ var errorFn = function (err) {
164
+ var _a, _b;return reject((_b = (_a = _this.errFn) === null || _a === void 0 ? void 0 : _a.call(_this, err)) !== null && _b !== void 0 ? _b : err);
165
+ };
166
+ signal.addEventListener('abort', errorFn);
167
+ fetch(url, opts).then(function (response) {
168
+ if (response.status >= 200 && response.status < 300) {
169
+ return _this.getDataByType(opts.type, response);
170
+ }
171
+ return errorFn(response.statusText);
172
+ }).then(function (res) {
173
+ var _a, _b;return resolve((_b = (_a = _this.resFn) === null || _a === void 0 ? void 0 : _a.call(_this, res)) !== null && _b !== void 0 ? _b : res);
174
+ }).catch(errorFn).finally(function () {
175
+ return clearTimeout(timer);
176
+ });
177
+ return promise;
178
+ };
179
+ _this.http = function (url, opts) {
180
+ var _a = (0, index_js_1.defer)(),
181
+ promise = _a.promise,
182
+ resolve = _a.resolve,
183
+ reject = _a.reject;
184
+ return promise;
185
+ };
186
+ _this.GET = function (url, query, _, opts) {
187
+ if (query === void 0) {
188
+ query = {};
189
+ }
190
+ return _this.request(url, __assign({ query: query, method: "GET" }, opts));
191
+ };
192
+ _this.POST = function (url, query, body, opts) {
193
+ if (query === void 0) {
194
+ query = {};
195
+ }
196
+ return _this.request(url, __assign({ query: query, method: "POST", body: body }, opts));
197
+ };
198
+ _this.PUT = function (url, query, body, opts) {
199
+ if (query === void 0) {
200
+ query = {};
201
+ }
202
+ return _this.request(url, __assign({ query: query, method: "PUT", body: body }, opts));
203
+ };
204
+ _this.DELETE = function (url, query, body, opts) {
205
+ if (query === void 0) {
206
+ query = {};
207
+ }
208
+ return _this.request(url, __assign({ query: query, method: "DELETE", body: body }, opts));
209
+ };
210
+ _this.OPTION = function (url, query, body, opts) {
211
+ if (query === void 0) {
212
+ query = {};
213
+ }
214
+ return _this.request(url, __assign({ query: query, method: "DELETE", body: body }, opts));
215
+ };
216
+ _this.request = _this.requestType();
217
+ return _this;
218
+ }
219
+ return Request;
220
+ }(RequestBase);
221
+ exports.Request = Request;
@@ -15,6 +15,7 @@ export declare type IRandomNum = (min: number, max: number, bool?: boolean) => n
15
15
  export declare type IUrlSplit = (url: string) => IObject<any>;
16
16
  export declare type IUrlJoin = (url: string, query: object) => string;
17
17
  export declare type IGetType<T> = (data: any) => typeof data | T[keyof T] | "null";
18
+ export declare type IGetTypeByList = (data: any, whiteList: string[]) => boolean;
18
19
  export declare type IGetValue = <T>(object: IObject<T> | IObject<T>[IKey], key: string, defaultValue?: any) => IObject<T>[IKey];
19
20
  export declare type ISetValue = <T>(object: IObject<T>, key: string, value?: any) => IObject<T>;
20
21
  export declare type IMixIn = <U extends IObject<any>>(target?: U, source?: IObject<any>, overwrite?: boolean) => U;
@@ -25,6 +26,8 @@ export declare type ICreateObject = <T, U extends T>(source: T) => U;
25
26
  export declare type IInherit = <T extends Function>(source: T, target?: Function) => Function;
26
27
  export declare type IGetInstance = (classProto: IInstance<FunctionConstructor>, overwrite?: boolean, ...params: any[]) => Function;
27
28
  export declare type IClassDecorator = (params: IObject<any>) => <TFunction extends Function>(target: TFunction) => void;
29
+ export declare type IStringToJson = (target: string) => IObject<any>;
30
+ export declare type IJsonToString = (target: IObject<any>) => string;
28
31
  export declare type IThrottle = (fn: Function, time: number) => (...args: any[]) => void;
29
32
  export declare type IDebounce = (fn: Function, time: number) => (...args: any[]) => void;
30
33
  export declare type IDefer = () => IPromise;
@@ -44,11 +47,43 @@ export declare type IStopBubble = (e: Event) => void;
44
47
  export declare type IStopDefault = (e: Event) => void;
45
48
  export declare type IRemoveHandler = <T extends Document>(ele: T, type: string, handler: (e: Event) => void) => void;
46
49
  export declare type IDispatchEvent = <T extends Document>(ele: T, data: any) => void;
47
- export declare type IRequest = {
50
+ export declare type IRequestParams<T> = T | IObject<any> | null;
51
+ export declare type IDataType = "text" | "json" | "blob" | "formData" | "arrayBuffer";
52
+ export declare type IRequestMethods = "GET" | "POST" | "DELETE" | "PUT" | "OPTION";
53
+ export declare type IRequestBody = IRequestParams<BodyInit>;
54
+ export declare type IRequestHeaders = IRequestParams<HeadersInit>;
55
+ export declare type IRequestFn = (url: string, params: IObject<any>, body: IRequestBody, opts: IRequestOptions) => Promise<any>;
56
+ export declare type IRequestOptions = {
57
+ method?: IRequestMethods;
58
+ query?: IRequestParams<IObject<any>>;
59
+ body?: IRequestBody;
60
+ headers?: IRequestHeaders;
61
+ abort?: AbortController;
62
+ timeout?: number;
63
+ [key: string]: any;
64
+ };
65
+ export declare type IInterceptors = {
66
+ use(type: "request" | "response" | "error", fn: Function): void;
67
+ get reqFn(): Function;
68
+ get resFn(): Function;
69
+ get errFn(): Function;
70
+ };
71
+ export declare type IRequestBase = {
48
72
  origin: string;
49
- fixOrigin: <T = string>(origin: T) => IRequest;
73
+ fixOrigin: (fixStr: string) => string;
50
74
  envDesc: () => "Window" | "Node";
51
- fetch: () => Promise<Response>;
75
+ chackUrl: (url: string) => boolean;
76
+ fetch: (url: string, opts: IRequestOptions) => Promise<any>;
77
+ http: (url: string, opts: IRequestOptions) => Promise<any>;
78
+ initFetchParams: (url: string, opts: IRequestOptions) => any;
79
+ getDataByType: (type: IDataType, response: Response) => Promise<any>;
52
80
  };
53
- export declare type IGet = (url: string, params: IObject<any>) => Promise<void>;
81
+ export declare type IRequest = {
82
+ request: Function;
83
+ GET: IRequestFn;
84
+ POST: IRequestFn;
85
+ DELETE: IRequestFn;
86
+ PUT: IRequestFn;
87
+ OPTION: IRequestFn;
88
+ } & IRequestBase;
54
89
  export {};
@@ -1,5 +1,6 @@
1
- import { IRandomNum, IUrlSplit, IUrlJoin, IGetType, types } from "./index.js";
1
+ import { IRandomNum, IUrlSplit, IUrlJoin, IGetType, IGetTypeByList, types } from "./index.js";
2
2
  export declare const randomNum: IRandomNum;
3
3
  export declare const urlSplit: IUrlSplit;
4
4
  export declare const urlJoin: IUrlJoin;
5
5
  export declare const getType: IGetType<types>;
6
+ export declare const getTypeByList: IGetTypeByList;
package/dist/esm/base.js CHANGED
@@ -18,7 +18,12 @@ export var urlSplit = function (url) {
18
18
  return result;
19
19
  };
20
20
  export var urlJoin = function (url, query) {
21
- var params = Object.keys(query).map(function (i) {
21
+ if (query === void 0) {
22
+ query = {};
23
+ }
24
+ var queryObject = Object.keys(query);
25
+ if (queryObject.length === 0) return url;
26
+ var params = queryObject.map(function (i) {
22
27
  return "".concat(i, "=").concat(query[i]);
23
28
  });
24
29
  return "".concat(url).concat(url.includes("?") ? "&" : '?').concat(params.join("&"));
@@ -32,4 +37,11 @@ export var getType = function (data) {
32
37
  return types[key];
33
38
  }
34
39
  return type;
40
+ };
41
+ export var getTypeByList = function (data, whiteList) {
42
+ if (whiteList === void 0) {
43
+ whiteList = [];
44
+ }
45
+ var __type = getType(data);
46
+ return whiteList.indexOf(__type) > 0;
35
47
  };
@@ -1,4 +1,4 @@
1
- import { IGetValue, ISetValue, IMixIn, ICloneDeep, ICreateObjectVariable, IEnumInversion, IInherit, ICreateObject, IGetInstance, IClassDecorator } from "./index.js";
1
+ import { IGetValue, ISetValue, IMixIn, ICloneDeep, ICreateObjectVariable, IEnumInversion, IInherit, ICreateObject, IGetInstance, IClassDecorator, IStringToJson, IJsonToString } from "./index.js";
2
2
  export declare const getValue: IGetValue;
3
3
  export declare const setValue: ISetValue;
4
4
  export declare const mixIn: IMixIn;
@@ -10,3 +10,5 @@ export declare const createObject: ICreateObject;
10
10
  export declare const inherit: IInherit;
11
11
  export declare const getInstance: IGetInstance;
12
12
  export declare const classDecorator: IClassDecorator;
13
+ export declare const stringToJson: IStringToJson;
14
+ export declare const jsonToString: IJsonToString;
@@ -7,7 +7,7 @@ var __spreadArray = this && this.__spreadArray || function (to, from, pack) {
7
7
  }
8
8
  return to.concat(ar || Array.prototype.slice.call(from));
9
9
  };
10
- import { getType } from "./index.js";
10
+ import { getType, getTypeByList } from "./index.js";
11
11
  export var getValue = function (object, key, defaultValue) {
12
12
  if (defaultValue === void 0) {
13
13
  defaultValue = '';
@@ -149,4 +149,20 @@ export var classDecorator = function (params) {
149
149
  }
150
150
  }
151
151
  };
152
+ };
153
+ export var stringToJson = function (target) {
154
+ if (getType(target) !== "string") return {};
155
+ try {
156
+ return JSON.parse(target);
157
+ } catch (error) {
158
+ return {};
159
+ }
160
+ };
161
+ export var jsonToString = function (target) {
162
+ if (!getTypeByList(target, ["array", "object", "set", "map"])) return "";
163
+ try {
164
+ return JSON.stringify(target);
165
+ } catch (error) {
166
+ return "";
167
+ }
152
168
  };
@@ -1,15 +1,42 @@
1
- import { IRequest } from "./index.js";
2
- export declare class Request implements IRequest {
1
+ import { IRequest, IRequestBase, IInterceptors } from "./index.js";
2
+ export declare class Interceptors implements IInterceptors {
3
+ private requestSuccess;
4
+ private responseSuccess;
5
+ private error;
6
+ use(type: any, fn: any): this;
7
+ get reqFn(): Function;
8
+ get resFn(): Function;
9
+ get errFn(): Function;
10
+ }
11
+ export declare abstract class RequestBase extends Interceptors implements IRequestBase {
3
12
  origin: string;
4
- constructor();
5
- fixOrigin(origin: any): this;
6
- envDesc(): "Window" | "Node";
7
- ajax(url: any, opts: any): void;
8
- fetch(): Promise<Response>;
9
- http(): void;
13
+ constructor(origin: any);
14
+ abstract fetch(url: any, opts: any): Promise<void>;
15
+ abstract http(url: any, opts: any): Promise<void>;
16
+ chackUrl: (url: any) => any;
17
+ fixOrigin: (fixStr: string) => string;
18
+ envDesc: () => "Window" | "Node";
19
+ requestType: () => (url: any, opts: any) => Promise<void>;
20
+ initFetchParams: (url: any, { method, query, headers, body, timeout, abort, type, ...others }: {
21
+ [x: string]: any;
22
+ method?: string;
23
+ query?: {};
24
+ headers?: {};
25
+ body?: any;
26
+ timeout?: number;
27
+ abort?: AbortController;
28
+ type?: string;
29
+ }) => any;
30
+ getDataByType: (type: any, response: any) => any;
31
+ }
32
+ export declare class Request extends RequestBase implements IRequest {
33
+ request: Function;
34
+ constructor(origin: any);
35
+ fetch: (_url: any, _opts: any) => Promise<void>;
36
+ http: (url: any, opts: any) => Promise<void>;
37
+ GET: (url: any, query: {}, _: any, opts: any) => any;
38
+ POST: (url: any, query: {}, body: any, opts: any) => any;
39
+ PUT: (url: any, query: {}, body: any, opts: any) => any;
40
+ DELETE: (url: any, query: {}, body: any, opts: any) => any;
41
+ OPTION: (url: any, query: {}, body: any, opts: any) => any;
10
42
  }
11
- export declare const GET: () => void;
12
- export declare const POST: () => void;
13
- export declare const PUT: () => void;
14
- export declare const DELETE: () => void;
15
- export declare const OPTION: () => void;
@@ -1,56 +1,217 @@
1
- import { defer } from "./index.js";
2
- var Request = function () {
3
- function Request() {}
4
- Request.prototype.fixOrigin = function (origin) {
5
- this.origin = origin;
6
- return this;
1
+ var __extends = this && this.__extends || function () {
2
+ var extendStatics = function (d, b) {
3
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
4
+ d.__proto__ = b;
5
+ } || function (d, b) {
6
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
7
+ };
8
+ return extendStatics(d, b);
7
9
  };
8
- Request.prototype.envDesc = function () {
9
- if (Window) {
10
- return "Window";
10
+ return function (d, b) {
11
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() {
14
+ this.constructor = d;
11
15
  }
12
- return "Node";
16
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
17
  };
14
- Request.prototype.ajax = function (url, opts) {
15
- var _a = defer(),
16
- promise = _a.promise,
17
- resolve = _a.resolve,
18
- reject = _a.reject;
19
- var _b = opts.method,
20
- method = _b === void 0 ? "GET" : _b,
21
- _c = opts.params,
22
- params = _c === void 0 ? {} : _c,
23
- _d = opts.body,
24
- body = _d === void 0 ? {} : _d,
25
- _e = opts.async,
26
- async = _e === void 0 ? true : _e,
27
- _f = opts.timeout,
28
- timeout = _f === void 0 ? 30 * 1000 : _f;
29
- var xhr = new XMLHttpRequest();
30
- switch (method) {
31
- case 'GET':
18
+ }();
19
+ var __assign = this && this.__assign || function () {
20
+ __assign = Object.assign || function (t) {
21
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
22
+ s = arguments[i];
23
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
24
+ }
25
+ return t;
26
+ };
27
+ return __assign.apply(this, arguments);
28
+ };
29
+ var __rest = this && this.__rest || function (s, e) {
30
+ var t = {};
31
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
32
+ if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
33
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
34
+ }
35
+ return t;
36
+ };
37
+ import { urlJoin, defer, jsonToString } from "./index.js";
38
+ var Interceptors = function () {
39
+ function Interceptors() {}
40
+ Interceptors.prototype.use = function (type, fn) {
41
+ switch (type) {
42
+ case "request":
43
+ this.requestSuccess = fn;
44
+ break;
45
+ case "response":
46
+ this.responseSuccess = fn;
32
47
  break;
33
- default:
48
+ case "error":
49
+ this.error = fn;
34
50
  break;
35
51
  }
36
- xhr.addEventListener('load', function () {
37
- if (xhr.readyState === 4 && xhr.status === 200) {
38
- try {} catch (error) {}
39
- } else {}
40
- });
41
- xhr.open(method, url, async);
42
- xhr.send(body);
43
- xhr.timeout = async && timeout;
44
- };
45
- Request.prototype.fetch = function () {
46
- return fetch("");
52
+ return this;
47
53
  };
48
- Request.prototype.http = function () {};
49
- return Request;
54
+ Object.defineProperty(Interceptors.prototype, "reqFn", {
55
+ get: function () {
56
+ return this.requestSuccess;
57
+ },
58
+ enumerable: false,
59
+ configurable: true
60
+ });
61
+ Object.defineProperty(Interceptors.prototype, "resFn", {
62
+ get: function () {
63
+ return this.responseSuccess;
64
+ },
65
+ enumerable: false,
66
+ configurable: true
67
+ });
68
+ Object.defineProperty(Interceptors.prototype, "errFn", {
69
+ get: function () {
70
+ return this.error;
71
+ },
72
+ enumerable: false,
73
+ configurable: true
74
+ });
75
+ return Interceptors;
50
76
  }();
51
- export { Request };
52
- export var GET = function () {};
53
- export var POST = function () {};
54
- export var PUT = function () {};
55
- export var DELETE = function () {};
56
- export var OPTION = function () {};
77
+ export { Interceptors };
78
+ var RequestBase = function (_super) {
79
+ __extends(RequestBase, _super);
80
+ function RequestBase(origin) {
81
+ var _this = _super.call(this) || this;
82
+ _this.chackUrl = function (url) {
83
+ return url.startsWith('/');
84
+ };
85
+ _this.fixOrigin = function (fixStr) {
86
+ if (_this.chackUrl(fixStr)) return _this.origin + fixStr;
87
+ return fixStr;
88
+ };
89
+ _this.envDesc = function () {
90
+ if (Window) {
91
+ return "Window";
92
+ }
93
+ return "Node";
94
+ };
95
+ _this.requestType = function () {
96
+ switch (_this.envDesc()) {
97
+ case "Window":
98
+ return _this.fetch;
99
+ case "Node":
100
+ return _this.http;
101
+ }
102
+ };
103
+ _this.initFetchParams = function (url, _a) {
104
+ var _b, _c;
105
+ var _d = _a.method,
106
+ method = _d === void 0 ? "GET" : _d,
107
+ _e = _a.query,
108
+ query = _e === void 0 ? {} : _e,
109
+ _f = _a.headers,
110
+ headers = _f === void 0 ? {} : _f,
111
+ _g = _a.body,
112
+ body = _g === void 0 ? null : _g,
113
+ _h = _a.timeout,
114
+ timeout = _h === void 0 ? 30 * 1000 : _h,
115
+ _j = _a.abort,
116
+ abort = _j === void 0 ? new AbortController() : _j,
117
+ _k = _a.type,
118
+ type = _k === void 0 ? "json" : _k,
119
+ others = __rest(_a, ["method", "query", "headers", "body", "timeout", "abort", "type"]);
120
+ url = urlJoin(_this.fixOrigin(url), query);
121
+ var timer = setTimeout(function () {
122
+ return abort.abort();
123
+ }, timeout);
124
+ var params = __assign({ url: url, method: method, headers: headers, body: method === "GET" ? null : jsonToString(body), timeout: timeout, timer: timer, signal: abort.signal, type: type }, others);
125
+ return (_c = (_b = _this.reqFn) === null || _b === void 0 ? void 0 : _b.call(_this, params)) !== null && _c !== void 0 ? _c : params;
126
+ };
127
+ _this.getDataByType = function (type, response) {
128
+ switch (type) {
129
+ case "text":
130
+ case "json":
131
+ case "blob":
132
+ case "formData":
133
+ case "arrayBuffer":
134
+ return response[type]();
135
+ default:
136
+ return response['json']();
137
+ }
138
+ };
139
+ _this.origin = origin !== null && origin !== void 0 ? origin : '';
140
+ return _this;
141
+ }
142
+ return RequestBase;
143
+ }(Interceptors);
144
+ export { RequestBase };
145
+ var Request = function (_super) {
146
+ __extends(Request, _super);
147
+ function Request(origin) {
148
+ var _this = _super.call(this, origin) || this;
149
+ _this.fetch = function (_url, _opts) {
150
+ var _a = defer(),
151
+ promise = _a.promise,
152
+ resolve = _a.resolve,
153
+ reject = _a.reject;
154
+ var _b = _this.initFetchParams(_url, _opts),
155
+ url = _b.url,
156
+ opts = __rest(_b, ["url"]);
157
+ var signal = opts.signal,
158
+ timer = opts.timer;
159
+ var errorFn = function (err) {
160
+ var _a, _b;return reject((_b = (_a = _this.errFn) === null || _a === void 0 ? void 0 : _a.call(_this, err)) !== null && _b !== void 0 ? _b : err);
161
+ };
162
+ signal.addEventListener('abort', errorFn);
163
+ fetch(url, opts).then(function (response) {
164
+ if (response.status >= 200 && response.status < 300) {
165
+ return _this.getDataByType(opts.type, response);
166
+ }
167
+ return errorFn(response.statusText);
168
+ }).then(function (res) {
169
+ var _a, _b;return resolve((_b = (_a = _this.resFn) === null || _a === void 0 ? void 0 : _a.call(_this, res)) !== null && _b !== void 0 ? _b : res);
170
+ }).catch(errorFn).finally(function () {
171
+ return clearTimeout(timer);
172
+ });
173
+ return promise;
174
+ };
175
+ _this.http = function (url, opts) {
176
+ var _a = defer(),
177
+ promise = _a.promise,
178
+ resolve = _a.resolve,
179
+ reject = _a.reject;
180
+ return promise;
181
+ };
182
+ _this.GET = function (url, query, _, opts) {
183
+ if (query === void 0) {
184
+ query = {};
185
+ }
186
+ return _this.request(url, __assign({ query: query, method: "GET" }, opts));
187
+ };
188
+ _this.POST = function (url, query, body, opts) {
189
+ if (query === void 0) {
190
+ query = {};
191
+ }
192
+ return _this.request(url, __assign({ query: query, method: "POST", body: body }, opts));
193
+ };
194
+ _this.PUT = function (url, query, body, opts) {
195
+ if (query === void 0) {
196
+ query = {};
197
+ }
198
+ return _this.request(url, __assign({ query: query, method: "PUT", body: body }, opts));
199
+ };
200
+ _this.DELETE = function (url, query, body, opts) {
201
+ if (query === void 0) {
202
+ query = {};
203
+ }
204
+ return _this.request(url, __assign({ query: query, method: "DELETE", body: body }, opts));
205
+ };
206
+ _this.OPTION = function (url, query, body, opts) {
207
+ if (query === void 0) {
208
+ query = {};
209
+ }
210
+ return _this.request(url, __assign({ query: query, method: "DELETE", body: body }, opts));
211
+ };
212
+ _this.request = _this.requestType();
213
+ return _this;
214
+ }
215
+ return Request;
216
+ }(RequestBase);
217
+ export { Request };
@@ -15,6 +15,7 @@ export declare type IRandomNum = (min: number, max: number, bool?: boolean) => n
15
15
  export declare type IUrlSplit = (url: string) => IObject<any>;
16
16
  export declare type IUrlJoin = (url: string, query: object) => string;
17
17
  export declare type IGetType<T> = (data: any) => typeof data | T[keyof T] | "null";
18
+ export declare type IGetTypeByList = (data: any, whiteList: string[]) => boolean;
18
19
  export declare type IGetValue = <T>(object: IObject<T> | IObject<T>[IKey], key: string, defaultValue?: any) => IObject<T>[IKey];
19
20
  export declare type ISetValue = <T>(object: IObject<T>, key: string, value?: any) => IObject<T>;
20
21
  export declare type IMixIn = <U extends IObject<any>>(target?: U, source?: IObject<any>, overwrite?: boolean) => U;
@@ -25,6 +26,8 @@ export declare type ICreateObject = <T, U extends T>(source: T) => U;
25
26
  export declare type IInherit = <T extends Function>(source: T, target?: Function) => Function;
26
27
  export declare type IGetInstance = (classProto: IInstance<FunctionConstructor>, overwrite?: boolean, ...params: any[]) => Function;
27
28
  export declare type IClassDecorator = (params: IObject<any>) => <TFunction extends Function>(target: TFunction) => void;
29
+ export declare type IStringToJson = (target: string) => IObject<any>;
30
+ export declare type IJsonToString = (target: IObject<any>) => string;
28
31
  export declare type IThrottle = (fn: Function, time: number) => (...args: any[]) => void;
29
32
  export declare type IDebounce = (fn: Function, time: number) => (...args: any[]) => void;
30
33
  export declare type IDefer = () => IPromise;
@@ -44,11 +47,43 @@ export declare type IStopBubble = (e: Event) => void;
44
47
  export declare type IStopDefault = (e: Event) => void;
45
48
  export declare type IRemoveHandler = <T extends Document>(ele: T, type: string, handler: (e: Event) => void) => void;
46
49
  export declare type IDispatchEvent = <T extends Document>(ele: T, data: any) => void;
47
- export declare type IRequest = {
50
+ export declare type IRequestParams<T> = T | IObject<any> | null;
51
+ export declare type IDataType = "text" | "json" | "blob" | "formData" | "arrayBuffer";
52
+ export declare type IRequestMethods = "GET" | "POST" | "DELETE" | "PUT" | "OPTION";
53
+ export declare type IRequestBody = IRequestParams<BodyInit>;
54
+ export declare type IRequestHeaders = IRequestParams<HeadersInit>;
55
+ export declare type IRequestFn = (url: string, params: IObject<any>, body: IRequestBody, opts: IRequestOptions) => Promise<any>;
56
+ export declare type IRequestOptions = {
57
+ method?: IRequestMethods;
58
+ query?: IRequestParams<IObject<any>>;
59
+ body?: IRequestBody;
60
+ headers?: IRequestHeaders;
61
+ abort?: AbortController;
62
+ timeout?: number;
63
+ [key: string]: any;
64
+ };
65
+ export declare type IInterceptors = {
66
+ use(type: "request" | "response" | "error", fn: Function): void;
67
+ get reqFn(): Function;
68
+ get resFn(): Function;
69
+ get errFn(): Function;
70
+ };
71
+ export declare type IRequestBase = {
48
72
  origin: string;
49
- fixOrigin: <T = string>(origin: T) => IRequest;
73
+ fixOrigin: (fixStr: string) => string;
50
74
  envDesc: () => "Window" | "Node";
51
- fetch: () => Promise<Response>;
75
+ chackUrl: (url: string) => boolean;
76
+ fetch: (url: string, opts: IRequestOptions) => Promise<any>;
77
+ http: (url: string, opts: IRequestOptions) => Promise<any>;
78
+ initFetchParams: (url: string, opts: IRequestOptions) => any;
79
+ getDataByType: (type: IDataType, response: Response) => Promise<any>;
52
80
  };
53
- export declare type IGet = (url: string, params: IObject<any>) => Promise<void>;
81
+ export declare type IRequest = {
82
+ request: Function;
83
+ GET: IRequestFn;
84
+ POST: IRequestFn;
85
+ DELETE: IRequestFn;
86
+ PUT: IRequestFn;
87
+ OPTION: IRequestFn;
88
+ } & IRequestBase;
54
89
  export {};
package/index.html CHANGED
@@ -9,7 +9,29 @@
9
9
  <body>
10
10
  <script type="module">
11
11
  import { Request } from "./dist/esm/request.js";
12
- console.log(Request);
12
+ const resource = new Request("http://127.0.0.1:1024");
13
+ resource
14
+ .use("request", (params) => {
15
+ return params;
16
+ })
17
+ .use("response", (params) => {
18
+ return params;
19
+ })
20
+ .use("error", (error) => {
21
+ console.log(error)
22
+ return error;
23
+ });
24
+ resource
25
+ .GET(
26
+ "/getList",
27
+ {
28
+ name: "hello",
29
+ age: 22,
30
+ },
31
+ {},
32
+ {}
33
+ )
34
+ .then((res) => console.log(res));
13
35
  </script>
14
36
  </body>
15
37
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "utils-lib-js",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "JavaScript工具函数,封装的一些常用的js函数",
5
5
  "main": "./dist/common/index.js",
6
6
  "types": "./dist/common/index.d.ts",