@gopowerteam/request 0.1.21 → 0.2.0

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/index.js DELETED
@@ -1,312 +0,0 @@
1
- import {
2
- __publicField
3
- } from "./chunk-XXPGZHWZ.js";
4
-
5
- // src/interfaces/request-generate.interface.ts
6
- var RequestGenerateType = /* @__PURE__ */ ((RequestGenerateType2) => {
7
- RequestGenerateType2["Request"] = "TO_REQUEST";
8
- RequestGenerateType2["URL"] = "TO_URL";
9
- return RequestGenerateType2;
10
- })(RequestGenerateType || {});
11
-
12
- // src/interfaces/request-plugin.interface.ts
13
- var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
14
- PluginLifecycle2["before"] = "before";
15
- PluginLifecycle2["after"] = "after";
16
- PluginLifecycle2["catch"] = "catch";
17
- return PluginLifecycle2;
18
- })(PluginLifecycle || {});
19
-
20
- // src/interfaces/request-send.interface.ts
21
- var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
22
- RequestMethod2["Get"] = "GET";
23
- RequestMethod2["Post"] = "POST";
24
- RequestMethod2["Put"] = "PUT";
25
- RequestMethod2["Delete"] = "DELETE";
26
- RequestMethod2["Options"] = "OPTIONS";
27
- RequestMethod2["Head"] = "HEAD";
28
- RequestMethod2["Patch"] = "PATCH";
29
- return RequestMethod2;
30
- })(RequestMethod || {});
31
-
32
- // src/utils/query-string.ts
33
- function encodeValue(value, encode) {
34
- if (!encode)
35
- return value;
36
- return encodeURIComponent(value);
37
- }
38
- function getKeyWithDot(key, childKey, allowDots) {
39
- return allowDots ? `${key}.${childKey}` : `${key}[${childKey}]`;
40
- }
41
- function processValue(value, options, parentKey = "") {
42
- const result = [];
43
- if (value === null || value === void 0) {
44
- if (!options.skipNulls) {
45
- result.push(`${parentKey}=`);
46
- }
47
- return result;
48
- }
49
- if (Array.isArray(value)) {
50
- if (options.arrayFormat === "comma") {
51
- const filteredValues = value.filter((item) => item !== null && item !== void 0);
52
- if (filteredValues.length > 0) {
53
- const commaValue = filteredValues.map(
54
- (item) => typeof item === "object" ? JSON.stringify(item) : item.toString()
55
- ).join(",");
56
- const shouldEncode = options.encode !== false;
57
- const encodedValue = encodeValue(commaValue, shouldEncode);
58
- result.push(`${parentKey}=${encodedValue}`);
59
- }
60
- } else {
61
- value.forEach((item, index) => {
62
- let itemKey;
63
- const shouldEncode = options.encode !== false;
64
- if (options.arrayFormat === "indices") {
65
- itemKey = parentKey ? `${parentKey}[${index}]` : `[${index}]`;
66
- } else if (options.arrayFormat === "brackets") {
67
- itemKey = parentKey ? `${parentKey}[]` : "[]";
68
- } else {
69
- itemKey = parentKey;
70
- }
71
- if (typeof item === "object" && item !== null) {
72
- result.push(...processValue(item, options, itemKey));
73
- } else {
74
- const encodedValue = encodeValue(item.toString(), shouldEncode);
75
- result.push(`${itemKey}=${encodedValue}`);
76
- }
77
- });
78
- }
79
- } else if (typeof value === "object") {
80
- Object.keys(value).forEach((childKey) => {
81
- const fullKey = parentKey ? getKeyWithDot(parentKey, childKey, options.allowDots || false) : childKey;
82
- result.push(...processValue(value[childKey], options, fullKey));
83
- });
84
- } else {
85
- const shouldEncode = options.encode !== false;
86
- const encodedValue = encodeValue(value.toString(), shouldEncode);
87
- const encodedKey = options.encodeValuesOnly ? parentKey : encodeValue(parentKey, shouldEncode);
88
- result.push(`${encodedKey}=${encodedValue}`);
89
- }
90
- return result;
91
- }
92
- function stringify(obj, options = {}) {
93
- const {
94
- arrayFormat = "indices",
95
- skipNulls = true,
96
- allowDots = true,
97
- encodeValuesOnly = false,
98
- encode = true,
99
- addQueryPrefix = false
100
- } = options;
101
- if (!obj || typeof obj !== "object") {
102
- return options.addQueryPrefix ? "?" : "";
103
- }
104
- const parts = [];
105
- Object.keys(obj).forEach((key) => {
106
- const value = obj[key];
107
- const processedValues = processValue(value, {
108
- arrayFormat,
109
- skipNulls,
110
- allowDots,
111
- encodeValuesOnly,
112
- encode,
113
- addQueryPrefix
114
- }, key);
115
- parts.push(...processedValues);
116
- });
117
- const queryString = parts.join("&");
118
- return addQueryPrefix ? queryString ? `?${queryString}` : "?" : queryString;
119
- }
120
-
121
- // src/request-service.ts
122
- var _RequestService = class {
123
- /**
124
- * 获取服务请求单例
125
- */
126
- static getInstance() {
127
- if (this.instance) {
128
- return this.instance;
129
- }
130
- return new _RequestService();
131
- }
132
- /**
133
- * 获取RequestAdatper
134
- * @returns RequestAdapter
135
- */
136
- getRequestAdapter() {
137
- if (!_RequestService.config.adapter) {
138
- throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
139
- }
140
- return _RequestService.config.adapter;
141
- }
142
- /**
143
- * 执行前置插件逻辑
144
- * @param plugins
145
- * @param options
146
- */
147
- async execRequestPlugin(plugins = [], options) {
148
- const extraParams = {};
149
- const appendParams = (params) => {
150
- Object.assign(extraParams, params || {});
151
- };
152
- for (const plugin of _RequestService.config.plugins) {
153
- if (plugin.before) {
154
- await plugin.before(options, appendParams);
155
- }
156
- }
157
- for (const plugin of plugins) {
158
- if (plugin.before) {
159
- await plugin.before(options, appendParams);
160
- }
161
- }
162
- return extraParams;
163
- }
164
- /**
165
- * 执行前置插件逻辑
166
- */
167
- execResponsePlugin(leftcycle, plugins = [], options, response) {
168
- plugins.forEach((plugin) => {
169
- const leftcycleFn = plugin[leftcycle];
170
- if (leftcycleFn) {
171
- leftcycleFn.bind(plugin)(response, options);
172
- }
173
- });
174
- _RequestService.config.plugins.forEach((plugin) => {
175
- const leftcycleFn = plugin[leftcycle];
176
- if (leftcycleFn) {
177
- leftcycleFn.bind(plugin)(response, options);
178
- }
179
- });
180
- }
181
- /**
182
- * 转换请求路径
183
- */
184
- parseRequestPath(path, paramsPath, service) {
185
- if (service) {
186
- path = `/${service}/${path}`.replace(/\/{2,3}/g, "/");
187
- }
188
- if (paramsPath) {
189
- return Object.entries(paramsPath).reduce(
190
- (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
191
- path
192
- );
193
- } else {
194
- return path;
195
- }
196
- }
197
- /**
198
- * 开始请求
199
- * @param adapter
200
- * @param options
201
- * @returns Promise
202
- */
203
- startRequest(adapter, options, extraParams) {
204
- return adapter.request({
205
- baseURL: _RequestService.config.gateway,
206
- pathURL: this.parseRequestPath(
207
- options.path,
208
- options.paramsPath,
209
- options.service
210
- ),
211
- method: options.method,
212
- headers: options.headers || {},
213
- paramsQuery: options.paramsQuery,
214
- paramsBody: options.paramsBody,
215
- extraParams
216
- });
217
- }
218
- /**
219
- * 执行拦截器
220
- * @param response 请求响应对象
221
- * @returns Promise
222
- */
223
- execInterceptors(response, hasException = false) {
224
- const interceptors = _RequestService.config?.interceptors;
225
- if (!interceptors?.status || !interceptors?.error || !interceptors?.success || !interceptors?.exception) {
226
- throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
227
- }
228
- const status = interceptors.status.exec(response) && !hasException;
229
- if (hasException) {
230
- interceptors.exception.exec(response);
231
- }
232
- if (status) {
233
- return Promise.resolve(interceptors.success.exec(response));
234
- } else {
235
- return Promise.reject(interceptors.error.exec(response));
236
- }
237
- }
238
- /**
239
- * 发送请求
240
- * @param {RequestSendOptions} options 请求选项
241
- * @param {RequestPlugin[]} requestPlugins 请求插件
242
- * @returns Promise
243
- */
244
- async send(options, requestPlugins = []) {
245
- if (!_RequestService.config) {
246
- throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
247
- }
248
- let hasException = false;
249
- const adapter = this.getRequestAdapter();
250
- const plugins = requestPlugins.filter(Boolean);
251
- const extraParams = await this.execRequestPlugin(plugins, options);
252
- const response = await this.startRequest(adapter, options, extraParams).then((response2) => adapter.transformResponse(response2)).catch((exception) => {
253
- hasException = true;
254
- return adapter.transformException(exception);
255
- });
256
- if (!hasException) {
257
- this.execResponsePlugin("after" /* after */, plugins, options, response);
258
- } else {
259
- this.execResponsePlugin("catch" /* catch */, plugins, options, response);
260
- }
261
- return this.execInterceptors(response, hasException);
262
- }
263
- /**
264
- * 生成请求路径
265
- * @param {RequestSendOptions} options 请求选项
266
- * @param {RequestPlugin[]} plugins 请求插件
267
- * @returns string
268
- */
269
- toURL(options, plugins = []) {
270
- if (!_RequestService.config) {
271
- throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
272
- }
273
- if (plugins && plugins.length) {
274
- this.execRequestPlugin(
275
- plugins.filter(Boolean),
276
- options
277
- );
278
- }
279
- const baseURL = _RequestService.config.gateway;
280
- const pathURL = this.parseRequestPath(
281
- options.path,
282
- options.paramsPath,
283
- options.service
284
- );
285
- const queryString = stringify(options.paramsQuery || {}, {
286
- arrayFormat: "repeat",
287
- skipNulls: true,
288
- allowDots: true,
289
- encodeValuesOnly: true,
290
- encode: true,
291
- addQueryPrefix: true,
292
- ..._RequestService.config.qs || {}
293
- });
294
- return `${baseURL}${pathURL}${queryString}`;
295
- }
296
- };
297
- var RequestService = _RequestService;
298
- __publicField(RequestService, "config");
299
- __publicField(RequestService, "instance");
300
-
301
- // src/request-setup.ts
302
- function setup(config) {
303
- RequestService.config = config;
304
- RequestService.config?.adapter?.injectConfig?.(config);
305
- }
306
- export {
307
- PluginLifecycle,
308
- RequestGenerateType,
309
- RequestMethod,
310
- RequestService,
311
- setup
312
- };
@@ -1,98 +0,0 @@
1
- import { IStringifyOptions } from 'qs';
2
-
3
- /**
4
- * 请求方法类型
5
- */
6
- declare enum RequestMethod {
7
- Get = "GET",
8
- Post = "POST",
9
- Put = "PUT",
10
- Delete = "DELETE",
11
- Options = "OPTIONS",
12
- Head = "HEAD",
13
- Patch = "PATCH"
14
- }
15
- interface RequestSendOptions {
16
- service?: string;
17
- path: string;
18
- method: RequestMethod | string;
19
- headers?: Record<string, string>;
20
- paramsPath?: Record<string, string | number>;
21
- paramsQuery?: Record<string, any>;
22
- paramsBody?: any;
23
- }
24
-
25
- /**
26
- * 请求插件
27
- */
28
- interface RequestPlugin {
29
- before?: (options: RequestSendOptions, appendParams: (params: Record<string, any>) => void) => void | Promise<void>;
30
- after?: (response: AdapterResponse, options: RequestSendOptions) => void;
31
- catch?: (response: AdapterResponse, options: RequestSendOptions) => void;
32
- }
33
- declare enum PluginLifecycle {
34
- before = "before",
35
- after = "after",
36
- catch = "catch"
37
- }
38
- type RequestLifecycle = PluginLifecycle.before;
39
- type ResponseLifecycle = PluginLifecycle.after | PluginLifecycle.catch;
40
-
41
- interface ResponseInterceptor {
42
- exec: (response: AdapterResponse) => any;
43
- }
44
-
45
- interface RequestSetupConfig {
46
- gateway: string;
47
- timeout?: number;
48
- qs?: IStringifyOptions;
49
- adapter?: RequestAdapter;
50
- interceptors: {
51
- status: ResponseInterceptor;
52
- success: ResponseInterceptor;
53
- error: ResponseInterceptor;
54
- exception: ResponseInterceptor;
55
- };
56
- plugins: RequestPlugin[];
57
- }
58
-
59
- interface RequestAdapter {
60
- /**
61
- * 注入全局配置文件
62
- * @param config
63
- * @returns
64
- */
65
- injectConfig?: (config: RequestSetupConfig) => void;
66
- /**
67
- * 发送请求
68
- */
69
- request: (options: RequestAdapterOptions) => Promise<any>;
70
- /**
71
- * 转换Response
72
- * @param any
73
- */
74
- transformResponse: (response: any) => AdapterResponse;
75
- /**
76
- * 转换Exception
77
- * @param any
78
- */
79
- transformException: (response: any) => AdapterResponse;
80
- }
81
- interface RequestAdapterOptions {
82
- baseURL: string;
83
- pathURL: string;
84
- headers: Record<string, string>;
85
- method: RequestMethod | string;
86
- paramsQuery?: Record<string, any>;
87
- paramsBody?: any;
88
- extraParams?: any;
89
- }
90
- interface AdapterResponse {
91
- data: Record<string, any>;
92
- status: number;
93
- statusText: string;
94
- headers: AdapterResponseHeaders;
95
- }
96
- type AdapterResponseHeaders = Record<string, string | string[] | number | boolean | undefined>;
97
-
98
- export { AdapterResponse as A, PluginLifecycle as P, RequestSetupConfig as R, RequestSendOptions as a, RequestPlugin as b, RequestAdapter as c, RequestAdapterOptions as d, AdapterResponseHeaders as e, RequestLifecycle as f, ResponseLifecycle as g, RequestMethod as h, ResponseInterceptor as i };