@gopowerteam/request 0.1.10 → 0.1.12

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.
@@ -19,6 +19,10 @@ var __copyProps = (to, from, except, desc) => {
19
19
  return to;
20
20
  };
21
21
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
26
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
27
  mod
24
28
  ));
@@ -37,110 +41,26 @@ module.exports = __toCommonJS(adapters_exports);
37
41
 
38
42
  // src/adapters/axios.adapter.ts
39
43
  var import_axios = __toESM(require("axios"), 1);
40
-
41
- // src/request-service.ts
42
- var _RequestService = class {
43
- static getInstance() {
44
- if (this.instance) {
45
- return this.instance;
46
- }
47
- return new _RequestService();
48
- }
49
- getRequestAdapter() {
50
- if (!_RequestService.config.adapter) {
51
- throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
52
- }
53
- return _RequestService.config.adapter;
54
- }
55
- execRequestPlugin(plugins = [], options) {
56
- _RequestService.config.plugins.forEach(
57
- (service) => service.before && service.before(options)
58
- );
59
- plugins.forEach((service) => service.before && service.before(options));
60
- }
61
- execResponsePlugin(leftcycle, plugins = [], options, response) {
62
- plugins.forEach((plugin) => {
63
- const leftcycleFn = plugin[leftcycle];
64
- leftcycleFn && leftcycleFn.bind(plugin)(response, options);
65
- });
66
- _RequestService.config.plugins.forEach((plugin) => {
67
- const leftcycleFn = plugin[leftcycle];
68
- leftcycleFn && leftcycleFn.bind(plugin)(response, options);
69
- });
70
- }
71
- parseRequestPath(path, paramsPath) {
72
- if (paramsPath) {
73
- return Object.entries(paramsPath).reduce(
74
- (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
75
- path
76
- );
77
- } else {
78
- return path;
79
- }
80
- }
81
- startRequest(adapter, options) {
82
- return adapter.request({
83
- baseURL: _RequestService.config.gateway,
84
- pathURL: this.parseRequestPath(options.path, options.paramsPath),
85
- method: options.method,
86
- headers: options.headers || {},
87
- paramsQuery: options.paramsQuery,
88
- paramsBody: options.paramsBody
89
- });
90
- }
91
- execInterceptors(response, hasException = false) {
92
- var _a;
93
- const interceptors = (_a = _RequestService.config) == null ? void 0 : _a.interceptors;
94
- if (!(interceptors == null ? void 0 : interceptors.status) || !(interceptors == null ? void 0 : interceptors.error) || !(interceptors == null ? void 0 : interceptors.success) || !(interceptors == null ? void 0 : interceptors.exception)) {
95
- throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
96
- }
97
- const status = interceptors.status.exec(response) && !hasException;
98
- if (hasException) {
99
- interceptors.exception.exec(response);
100
- }
101
- if (status) {
102
- return Promise.resolve(interceptors.success.exec(response));
103
- } else {
104
- return Promise.reject(interceptors.error.exec(response));
105
- }
106
- }
107
- async send(options, plugins = []) {
108
- if (!_RequestService.config) {
109
- throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
110
- }
111
- let hasException = false;
112
- const adapter = this.getRequestAdapter();
113
- this.execRequestPlugin(plugins, options);
114
- const response = await this.startRequest(adapter, options).then((response2) => adapter.transformResponse(response2)).catch((exception) => {
115
- hasException = true;
116
- return adapter.transformException(exception);
117
- });
118
- if (!hasException) {
119
- this.execResponsePlugin("after" /* after */, plugins, options, response);
120
- } else {
121
- this.execResponsePlugin("catch" /* catch */, plugins, options, response);
122
- }
123
- return this.execInterceptors(response, hasException);
124
- }
125
- };
126
- var RequestService = _RequestService;
127
- __publicField(RequestService, "config");
128
- __publicField(RequestService, "instance");
129
-
130
- // src/adapters/axios.adapter.ts
131
44
  var qs = __toESM(require("qs"), 1);
132
45
  var _AxiosAdapter = class {
46
+ config;
47
+ injectConfig(config) {
48
+ this.config = config;
49
+ }
50
+ /**
51
+ * 获取Axios实例
52
+ */
133
53
  getAxiosInstance() {
134
54
  if (!_AxiosAdapter.axiosInstance) {
135
55
  _AxiosAdapter.axiosInstance = import_axios.default.create({
136
- timeout: RequestService.config.timeout,
56
+ timeout: this.config?.timeout,
137
57
  headers: {
138
58
  "Content-Type": "application/json"
139
59
  },
140
60
  paramsSerializer: {
141
61
  serialize: (params) => qs.stringify(
142
62
  params,
143
- RequestService.config.qs || {
63
+ this.config?.qs || {
144
64
  arrayFormat: "repeat",
145
65
  skipNulls: true,
146
66
  allowDots: true,
@@ -153,6 +73,11 @@ var _AxiosAdapter = class {
153
73
  }
154
74
  return _AxiosAdapter.axiosInstance;
155
75
  }
76
+ /**
77
+ * 发送请求
78
+ * @param options 请求参数
79
+ * @returns AxiosResponse
80
+ */
156
81
  request({
157
82
  baseURL,
158
83
  pathURL,
@@ -171,6 +96,11 @@ var _AxiosAdapter = class {
171
96
  url: pathURL
172
97
  });
173
98
  }
99
+ /**
100
+ * 转换Response
101
+ * @param response
102
+ * @returns
103
+ */
174
104
  transformResponse(response) {
175
105
  return {
176
106
  data: response.data,
@@ -179,13 +109,17 @@ var _AxiosAdapter = class {
179
109
  headers: response.headers
180
110
  };
181
111
  }
112
+ /**
113
+ * 转换Response
114
+ * @param response
115
+ * @returns
116
+ */
182
117
  transformException(exception) {
183
- var _a, _b, _c, _d;
184
118
  return {
185
- data: ((_a = exception.response) == null ? void 0 : _a.data) || {},
186
- statusText: ((_b = exception.response) == null ? void 0 : _b.statusText) || "",
187
- status: ((_c = exception.response) == null ? void 0 : _c.status) || 400,
188
- headers: ((_d = exception.response) == null ? void 0 : _d.headers) || {}
119
+ data: exception.response?.data || {},
120
+ statusText: exception.response?.statusText || "",
121
+ status: exception.response?.status || 400,
122
+ headers: exception.response?.headers || {}
189
123
  };
190
124
  }
191
125
  };
@@ -1,8 +1,11 @@
1
- import { a as RequestAdapter, b as RequestAdapterOptions, A as AdapterResponse } from '../request-adapter.interface-bd32c0be.js';
1
+ import { c as RequestAdapter, R as RequestSetupConfig, d as RequestAdapterOptions, A as AdapterResponse } from '../request-plugin.interface-70aec02a.js';
2
2
  import { AxiosResponse, AxiosError } from 'axios';
3
+ import 'qs';
3
4
 
4
5
  declare class AxiosAdapter implements RequestAdapter {
5
6
  private static axiosInstance;
7
+ private config;
8
+ injectConfig(config: RequestSetupConfig): void;
6
9
  /**
7
10
  * 获取Axios实例
8
11
  */
@@ -1,23 +1,29 @@
1
1
  import {
2
- RequestService,
3
2
  __publicField
4
- } from "../chunk-WMRFSSUJ.js";
3
+ } from "../chunk-XXPGZHWZ.js";
5
4
 
6
5
  // src/adapters/axios.adapter.ts
7
6
  import axios from "axios";
8
7
  import * as qs from "qs";
9
8
  var _AxiosAdapter = class {
9
+ config;
10
+ injectConfig(config) {
11
+ this.config = config;
12
+ }
13
+ /**
14
+ * 获取Axios实例
15
+ */
10
16
  getAxiosInstance() {
11
17
  if (!_AxiosAdapter.axiosInstance) {
12
18
  _AxiosAdapter.axiosInstance = axios.create({
13
- timeout: RequestService.config.timeout,
19
+ timeout: this.config?.timeout,
14
20
  headers: {
15
21
  "Content-Type": "application/json"
16
22
  },
17
23
  paramsSerializer: {
18
24
  serialize: (params) => qs.stringify(
19
25
  params,
20
- RequestService.config.qs || {
26
+ this.config?.qs || {
21
27
  arrayFormat: "repeat",
22
28
  skipNulls: true,
23
29
  allowDots: true,
@@ -30,6 +36,11 @@ var _AxiosAdapter = class {
30
36
  }
31
37
  return _AxiosAdapter.axiosInstance;
32
38
  }
39
+ /**
40
+ * 发送请求
41
+ * @param options 请求参数
42
+ * @returns AxiosResponse
43
+ */
33
44
  request({
34
45
  baseURL,
35
46
  pathURL,
@@ -48,6 +59,11 @@ var _AxiosAdapter = class {
48
59
  url: pathURL
49
60
  });
50
61
  }
62
+ /**
63
+ * 转换Response
64
+ * @param response
65
+ * @returns
66
+ */
51
67
  transformResponse(response) {
52
68
  return {
53
69
  data: response.data,
@@ -56,13 +72,17 @@ var _AxiosAdapter = class {
56
72
  headers: response.headers
57
73
  };
58
74
  }
75
+ /**
76
+ * 转换Response
77
+ * @param response
78
+ * @returns
79
+ */
59
80
  transformException(exception) {
60
- var _a, _b, _c, _d;
61
81
  return {
62
- data: ((_a = exception.response) == null ? void 0 : _a.data) || {},
63
- statusText: ((_b = exception.response) == null ? void 0 : _b.statusText) || "",
64
- status: ((_c = exception.response) == null ? void 0 : _c.status) || 400,
65
- headers: ((_d = exception.response) == null ? void 0 : _d.headers) || {}
82
+ data: exception.response?.data || {},
83
+ statusText: exception.response?.statusText || "",
84
+ status: exception.response?.status || 400,
85
+ headers: exception.response?.headers || {}
66
86
  };
67
87
  }
68
88
  };
@@ -0,0 +1,10 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+
8
+ export {
9
+ __publicField
10
+ };
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
9
  var __export = (target, all) => {
@@ -16,6 +18,14 @@ var __copyProps = (to, from, except, desc) => {
16
18
  }
17
19
  return to;
18
20
  };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
19
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
30
  var __publicField = (obj, key, value) => {
21
31
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
@@ -26,12 +36,16 @@ var __publicField = (obj, key, value) => {
26
36
  var src_exports = {};
27
37
  __export(src_exports, {
28
38
  PluginLifecycle: () => PluginLifecycle,
39
+ RequestGenerateType: () => RequestGenerateType,
29
40
  RequestMethod: () => RequestMethod,
30
41
  RequestService: () => RequestService,
31
42
  setup: () => setup
32
43
  });
33
44
  module.exports = __toCommonJS(src_exports);
34
45
 
46
+ // src/request-service.ts
47
+ var import_qs = __toESM(require("qs"), 1);
48
+
35
49
  // src/interfaces/request-plugin.interface.ts
36
50
  var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
37
51
  PluginLifecycle2["before"] = "before";
@@ -42,24 +56,41 @@ var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
42
56
 
43
57
  // src/request-service.ts
44
58
  var _RequestService = class {
59
+ /**
60
+ * 获取服务请求单例
61
+ */
45
62
  static getInstance() {
46
63
  if (this.instance) {
47
64
  return this.instance;
48
65
  }
49
66
  return new _RequestService();
50
67
  }
68
+ /**
69
+ * 获取RequestAdatper
70
+ * @returns
71
+ */
51
72
  getRequestAdapter() {
52
73
  if (!_RequestService.config.adapter) {
53
74
  throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
54
75
  }
55
76
  return _RequestService.config.adapter;
56
77
  }
78
+ /**
79
+ * 执行前置插件逻辑
80
+ * @param plugins
81
+ * @param options
82
+ */
57
83
  execRequestPlugin(plugins = [], options) {
58
84
  _RequestService.config.plugins.forEach(
59
85
  (service) => service.before && service.before(options)
60
86
  );
61
87
  plugins.forEach((service) => service.before && service.before(options));
62
88
  }
89
+ /**
90
+ * 执行前置插件逻辑
91
+ * @param plugins
92
+ * @param options
93
+ */
63
94
  execResponsePlugin(leftcycle, plugins = [], options, response) {
64
95
  plugins.forEach((plugin) => {
65
96
  const leftcycleFn = plugin[leftcycle];
@@ -70,7 +101,13 @@ var _RequestService = class {
70
101
  leftcycleFn && leftcycleFn.bind(plugin)(response, options);
71
102
  });
72
103
  }
73
- parseRequestPath(path, paramsPath) {
104
+ /**
105
+ * 转换请求路径
106
+ */
107
+ parseRequestPath(path, paramsPath, service) {
108
+ if (service) {
109
+ path = `/${service}/${path}`.replace(/\/{2,3}/g, "/");
110
+ }
74
111
  if (paramsPath) {
75
112
  return Object.entries(paramsPath).reduce(
76
113
  (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
@@ -80,20 +117,34 @@ var _RequestService = class {
80
117
  return path;
81
118
  }
82
119
  }
120
+ /**
121
+ * 开始请求
122
+ * @param adapter
123
+ * @param options
124
+ * @returns
125
+ */
83
126
  startRequest(adapter, options) {
84
127
  return adapter.request({
85
128
  baseURL: _RequestService.config.gateway,
86
- pathURL: this.parseRequestPath(options.path, options.paramsPath),
129
+ pathURL: this.parseRequestPath(
130
+ options.path,
131
+ options.paramsPath,
132
+ options.service
133
+ ),
87
134
  method: options.method,
88
135
  headers: options.headers || {},
89
136
  paramsQuery: options.paramsQuery,
90
137
  paramsBody: options.paramsBody
91
138
  });
92
139
  }
140
+ /**
141
+ * 执行拦截器
142
+ * @param response 请求响应对象
143
+ * @returns
144
+ */
93
145
  execInterceptors(response, hasException = false) {
94
- var _a;
95
- const interceptors = (_a = _RequestService.config) == null ? void 0 : _a.interceptors;
96
- if (!(interceptors == null ? void 0 : interceptors.status) || !(interceptors == null ? void 0 : interceptors.error) || !(interceptors == null ? void 0 : interceptors.success) || !(interceptors == null ? void 0 : interceptors.exception)) {
146
+ const interceptors = _RequestService.config?.interceptors;
147
+ if (!interceptors?.status || !interceptors?.error || !interceptors?.success || !interceptors?.exception) {
97
148
  throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
98
149
  }
99
150
  const status = interceptors.status.exec(response) && !hasException;
@@ -106,6 +157,12 @@ var _RequestService = class {
106
157
  return Promise.reject(interceptors.error.exec(response));
107
158
  }
108
159
  }
160
+ /**
161
+ * 发送请求
162
+ * @param {RequestSendOptions} options 请求选项
163
+ * @param {RequestPlugin[]} plugins 请求插件
164
+ * @returns
165
+ */
109
166
  async send(options, plugins = []) {
110
167
  if (!_RequestService.config) {
111
168
  throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
@@ -124,6 +181,37 @@ var _RequestService = class {
124
181
  }
125
182
  return this.execInterceptors(response, hasException);
126
183
  }
184
+ /**
185
+ * 生成请求路径
186
+ * @param {RequestSendOptions} options 请求选项
187
+ * @param {RequestPlugin[]} plugins 请求插件
188
+ * @returns
189
+ */
190
+ toURL(options, plugins = []) {
191
+ if (!_RequestService.config) {
192
+ throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
193
+ }
194
+ if (plugins && plugins.length) {
195
+ this.execRequestPlugin(plugins, options);
196
+ }
197
+ const baseURL = _RequestService.config.gateway;
198
+ const pathURL = this.parseRequestPath(
199
+ options.path,
200
+ options.paramsPath,
201
+ options.service
202
+ );
203
+ const queryString = import_qs.default.stringify(
204
+ options.paramsQuery,
205
+ _RequestService.config.qs || {
206
+ arrayFormat: "repeat",
207
+ skipNulls: true,
208
+ allowDots: true,
209
+ encodeValuesOnly: true,
210
+ encode: true
211
+ }
212
+ );
213
+ return `${baseURL}${pathURL}${queryString}`;
214
+ }
127
215
  };
128
216
  var RequestService = _RequestService;
129
217
  __publicField(RequestService, "config");
@@ -132,6 +220,7 @@ __publicField(RequestService, "instance");
132
220
  // src/request-setup.ts
133
221
  function setup(config) {
134
222
  RequestService.config = config;
223
+ RequestService.config?.adapter?.injectConfig?.(config);
135
224
  }
136
225
 
137
226
  // src/interfaces/request-send.interface.ts
@@ -145,9 +234,17 @@ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
145
234
  RequestMethod2["Patch"] = "PATCH";
146
235
  return RequestMethod2;
147
236
  })(RequestMethod || {});
237
+
238
+ // src/interfaces/request-generate.interface.ts
239
+ var RequestGenerateType = /* @__PURE__ */ ((RequestGenerateType2) => {
240
+ RequestGenerateType2["Request"] = "TO_REQUEST";
241
+ RequestGenerateType2["URL"] = "TO_URL";
242
+ return RequestGenerateType2;
243
+ })(RequestGenerateType || {});
148
244
  // Annotate the CommonJS export names for ESM import in node:
149
245
  0 && (module.exports = {
150
246
  PluginLifecycle,
247
+ RequestGenerateType,
151
248
  RequestMethod,
152
249
  RequestService,
153
250
  setup
package/dist/index.d.ts CHANGED
@@ -1,40 +1,6 @@
1
- import { R as RequestSendOptions, A as AdapterResponse, a as RequestAdapter } from './request-adapter.interface-bd32c0be.js';
2
- export { A as AdapterResponse, a as RequestAdapter, b as RequestAdapterOptions, c as RequestMethod, R as RequestSendOptions } from './request-adapter.interface-bd32c0be.js';
3
- import { IStringifyOptions } from 'qs';
4
-
5
- /**
6
- * 请求插件
7
- */
8
- interface RequestPlugin {
9
- before?: (options: RequestSendOptions) => void;
10
- after?: (response: AdapterResponse, options: RequestSendOptions) => void;
11
- catch?: (response: AdapterResponse, options: RequestSendOptions) => void;
12
- }
13
- declare enum PluginLifecycle {
14
- before = "before",
15
- after = "after",
16
- catch = "catch"
17
- }
18
- declare type RequestLifecycle = PluginLifecycle.before;
19
- declare type ResponseLifecycle = PluginLifecycle.after | PluginLifecycle.catch;
20
-
21
- interface ResponseInterceptor {
22
- exec(response: AdapterResponse): any;
23
- }
24
-
25
- interface RequestSetupConfig {
26
- gateway: string;
27
- timeout?: number;
28
- qs?: IStringifyOptions;
29
- adapter?: RequestAdapter;
30
- interceptors: {
31
- status: ResponseInterceptor;
32
- success: ResponseInterceptor;
33
- error: ResponseInterceptor;
34
- exception: ResponseInterceptor;
35
- };
36
- plugins: RequestPlugin[];
37
- }
1
+ import { R as RequestSetupConfig, a as RequestSendOptions, b as RequestPlugin } from './request-plugin.interface-70aec02a.js';
2
+ export { A as AdapterResponse, e as AdapterResponseHeaders, P as PluginLifecycle, c as RequestAdapter, d as RequestAdapterOptions, f as RequestLifecycle, h as RequestMethod, i as ResponseInterceptor, g as ResponseLifecycle } from './request-plugin.interface-70aec02a.js';
3
+ import 'qs';
38
4
 
39
5
  declare class RequestService {
40
6
  static config: RequestSetupConfig;
@@ -84,8 +50,23 @@ declare class RequestService {
84
50
  * @returns
85
51
  */
86
52
  send(options: RequestSendOptions, plugins?: RequestPlugin[]): Promise<any>;
53
+ /**
54
+ * 生成请求路径
55
+ * @param {RequestSendOptions} options 请求选项
56
+ * @param {RequestPlugin[]} plugins 请求插件
57
+ * @returns
58
+ */
59
+ toURL(options: RequestSendOptions, plugins?: RequestPlugin[]): string;
87
60
  }
88
61
 
89
62
  declare function setup(config: RequestSetupConfig): void;
90
63
 
91
- export { PluginLifecycle, RequestLifecycle, RequestPlugin, RequestService, RequestSetupConfig, ResponseInterceptor, ResponseLifecycle, setup };
64
+ declare enum RequestGenerateType {
65
+ Request = "TO_REQUEST",
66
+ URL = "TO_URL"
67
+ }
68
+ interface RequestGenerateOptions {
69
+ type?: RequestGenerateType;
70
+ }
71
+
72
+ export { RequestGenerateOptions, RequestGenerateType, RequestPlugin, RequestSendOptions, RequestService, RequestSetupConfig, setup };
package/dist/index.js CHANGED
@@ -1,11 +1,185 @@
1
1
  import {
2
- PluginLifecycle,
3
- RequestService
4
- } from "./chunk-WMRFSSUJ.js";
2
+ __publicField
3
+ } from "./chunk-XXPGZHWZ.js";
4
+
5
+ // src/request-service.ts
6
+ import qs from "qs";
7
+
8
+ // src/interfaces/request-plugin.interface.ts
9
+ var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
10
+ PluginLifecycle2["before"] = "before";
11
+ PluginLifecycle2["after"] = "after";
12
+ PluginLifecycle2["catch"] = "catch";
13
+ return PluginLifecycle2;
14
+ })(PluginLifecycle || {});
15
+
16
+ // src/request-service.ts
17
+ var _RequestService = class {
18
+ /**
19
+ * 获取服务请求单例
20
+ */
21
+ static getInstance() {
22
+ if (this.instance) {
23
+ return this.instance;
24
+ }
25
+ return new _RequestService();
26
+ }
27
+ /**
28
+ * 获取RequestAdatper
29
+ * @returns
30
+ */
31
+ getRequestAdapter() {
32
+ if (!_RequestService.config.adapter) {
33
+ throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
34
+ }
35
+ return _RequestService.config.adapter;
36
+ }
37
+ /**
38
+ * 执行前置插件逻辑
39
+ * @param plugins
40
+ * @param options
41
+ */
42
+ execRequestPlugin(plugins = [], options) {
43
+ _RequestService.config.plugins.forEach(
44
+ (service) => service.before && service.before(options)
45
+ );
46
+ plugins.forEach((service) => service.before && service.before(options));
47
+ }
48
+ /**
49
+ * 执行前置插件逻辑
50
+ * @param plugins
51
+ * @param options
52
+ */
53
+ execResponsePlugin(leftcycle, plugins = [], options, response) {
54
+ plugins.forEach((plugin) => {
55
+ const leftcycleFn = plugin[leftcycle];
56
+ leftcycleFn && leftcycleFn.bind(plugin)(response, options);
57
+ });
58
+ _RequestService.config.plugins.forEach((plugin) => {
59
+ const leftcycleFn = plugin[leftcycle];
60
+ leftcycleFn && leftcycleFn.bind(plugin)(response, options);
61
+ });
62
+ }
63
+ /**
64
+ * 转换请求路径
65
+ */
66
+ parseRequestPath(path, paramsPath, service) {
67
+ if (service) {
68
+ path = `/${service}/${path}`.replace(/\/{2,3}/g, "/");
69
+ }
70
+ if (paramsPath) {
71
+ return Object.entries(paramsPath).reduce(
72
+ (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
73
+ path
74
+ );
75
+ } else {
76
+ return path;
77
+ }
78
+ }
79
+ /**
80
+ * 开始请求
81
+ * @param adapter
82
+ * @param options
83
+ * @returns
84
+ */
85
+ startRequest(adapter, options) {
86
+ return adapter.request({
87
+ baseURL: _RequestService.config.gateway,
88
+ pathURL: this.parseRequestPath(
89
+ options.path,
90
+ options.paramsPath,
91
+ options.service
92
+ ),
93
+ method: options.method,
94
+ headers: options.headers || {},
95
+ paramsQuery: options.paramsQuery,
96
+ paramsBody: options.paramsBody
97
+ });
98
+ }
99
+ /**
100
+ * 执行拦截器
101
+ * @param response 请求响应对象
102
+ * @returns
103
+ */
104
+ execInterceptors(response, hasException = false) {
105
+ const interceptors = _RequestService.config?.interceptors;
106
+ if (!interceptors?.status || !interceptors?.error || !interceptors?.success || !interceptors?.exception) {
107
+ throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
108
+ }
109
+ const status = interceptors.status.exec(response) && !hasException;
110
+ if (hasException) {
111
+ interceptors.exception.exec(response);
112
+ }
113
+ if (status) {
114
+ return Promise.resolve(interceptors.success.exec(response));
115
+ } else {
116
+ return Promise.reject(interceptors.error.exec(response));
117
+ }
118
+ }
119
+ /**
120
+ * 发送请求
121
+ * @param {RequestSendOptions} options 请求选项
122
+ * @param {RequestPlugin[]} plugins 请求插件
123
+ * @returns
124
+ */
125
+ async send(options, plugins = []) {
126
+ if (!_RequestService.config) {
127
+ throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
128
+ }
129
+ let hasException = false;
130
+ const adapter = this.getRequestAdapter();
131
+ this.execRequestPlugin(plugins, options);
132
+ const response = await this.startRequest(adapter, options).then((response2) => adapter.transformResponse(response2)).catch((exception) => {
133
+ hasException = true;
134
+ return adapter.transformException(exception);
135
+ });
136
+ if (!hasException) {
137
+ this.execResponsePlugin("after" /* after */, plugins, options, response);
138
+ } else {
139
+ this.execResponsePlugin("catch" /* catch */, plugins, options, response);
140
+ }
141
+ return this.execInterceptors(response, hasException);
142
+ }
143
+ /**
144
+ * 生成请求路径
145
+ * @param {RequestSendOptions} options 请求选项
146
+ * @param {RequestPlugin[]} plugins 请求插件
147
+ * @returns
148
+ */
149
+ toURL(options, plugins = []) {
150
+ if (!_RequestService.config) {
151
+ throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
152
+ }
153
+ if (plugins && plugins.length) {
154
+ this.execRequestPlugin(plugins, options);
155
+ }
156
+ const baseURL = _RequestService.config.gateway;
157
+ const pathURL = this.parseRequestPath(
158
+ options.path,
159
+ options.paramsPath,
160
+ options.service
161
+ );
162
+ const queryString = qs.stringify(
163
+ options.paramsQuery,
164
+ _RequestService.config.qs || {
165
+ arrayFormat: "repeat",
166
+ skipNulls: true,
167
+ allowDots: true,
168
+ encodeValuesOnly: true,
169
+ encode: true
170
+ }
171
+ );
172
+ return `${baseURL}${pathURL}${queryString}`;
173
+ }
174
+ };
175
+ var RequestService = _RequestService;
176
+ __publicField(RequestService, "config");
177
+ __publicField(RequestService, "instance");
5
178
 
6
179
  // src/request-setup.ts
7
180
  function setup(config) {
8
181
  RequestService.config = config;
182
+ RequestService.config?.adapter?.injectConfig?.(config);
9
183
  }
10
184
 
11
185
  // src/interfaces/request-send.interface.ts
@@ -19,8 +193,16 @@ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
19
193
  RequestMethod2["Patch"] = "PATCH";
20
194
  return RequestMethod2;
21
195
  })(RequestMethod || {});
196
+
197
+ // src/interfaces/request-generate.interface.ts
198
+ var RequestGenerateType = /* @__PURE__ */ ((RequestGenerateType2) => {
199
+ RequestGenerateType2["Request"] = "TO_REQUEST";
200
+ RequestGenerateType2["URL"] = "TO_URL";
201
+ return RequestGenerateType2;
202
+ })(RequestGenerateType || {});
22
203
  export {
23
204
  PluginLifecycle,
205
+ RequestGenerateType,
24
206
  RequestMethod,
25
207
  RequestService,
26
208
  setup
@@ -0,0 +1,97 @@
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
+ interface ResponseInterceptor {
26
+ exec(response: AdapterResponse): any;
27
+ }
28
+
29
+ interface RequestSetupConfig {
30
+ gateway: string;
31
+ timeout?: number;
32
+ qs?: IStringifyOptions;
33
+ adapter?: RequestAdapter;
34
+ interceptors: {
35
+ status: ResponseInterceptor;
36
+ success: ResponseInterceptor;
37
+ error: ResponseInterceptor;
38
+ exception: ResponseInterceptor;
39
+ };
40
+ plugins: RequestPlugin[];
41
+ }
42
+
43
+ interface RequestAdapter {
44
+ /**
45
+ * 注入全局配置文件
46
+ * @param config
47
+ * @returns
48
+ */
49
+ injectConfig?: (config: RequestSetupConfig) => void;
50
+ /**
51
+ * 发送请求
52
+ */
53
+ request(options: RequestAdapterOptions): Promise<any>;
54
+ /**
55
+ * 转换Response
56
+ * @param any
57
+ */
58
+ transformResponse(response: any): AdapterResponse;
59
+ /**
60
+ * 转换Exception
61
+ * @param any
62
+ */
63
+ transformException(response: any): AdapterResponse;
64
+ }
65
+ interface RequestAdapterOptions {
66
+ baseURL: string;
67
+ pathURL: string;
68
+ headers: Record<string, string>;
69
+ method: RequestMethod | string;
70
+ paramsQuery?: Record<string, any>;
71
+ paramsBody?: any;
72
+ }
73
+ interface AdapterResponse {
74
+ data: Record<string, any>;
75
+ status: number;
76
+ statusText: string;
77
+ headers: AdapterResponseHeaders;
78
+ }
79
+ type AdapterResponseHeaders = Record<string, string | string[] | number | boolean | undefined>;
80
+
81
+ /**
82
+ * 请求插件
83
+ */
84
+ interface RequestPlugin {
85
+ before?: (options: RequestSendOptions) => void;
86
+ after?: (response: AdapterResponse, options: RequestSendOptions) => void;
87
+ catch?: (response: AdapterResponse, options: RequestSendOptions) => void;
88
+ }
89
+ declare enum PluginLifecycle {
90
+ before = "before",
91
+ after = "after",
92
+ catch = "catch"
93
+ }
94
+ type RequestLifecycle = PluginLifecycle.before;
95
+ type ResponseLifecycle = PluginLifecycle.after | PluginLifecycle.catch;
96
+
97
+ 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 };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gopowerteam/request",
3
3
  "private": false,
4
- "version": "0.1.10",
4
+ "version": "0.1.12",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
@@ -28,18 +28,17 @@
28
28
  }
29
29
  },
30
30
  "devDependencies": {
31
- "@types/axios": "^0.14.0",
32
- "@types/jest": "^29.1.2",
33
- "@types/node": "16",
31
+ "@types/jest": "^29.4.0",
32
+ "@types/node": "18",
34
33
  "@types/qs": "^6.9.7",
35
- "jest": "^29.1.2",
36
- "ts-jest": "^29.0.3",
34
+ "jest": "^29.4.3",
35
+ "ts-jest": "^29.0.5",
37
36
  "ts-node": "^10.9.1",
38
- "tsup": "^6.2.3",
39
- "typescript": "^4.8.4"
37
+ "tsup": "^6.6.3",
38
+ "typescript": "^4.9.5"
40
39
  },
41
40
  "dependencies": {
42
- "axios": "^1.1.2",
41
+ "axios": "^1.3.4",
43
42
  "qs": "^6.11.0"
44
43
  },
45
44
  "scripts": {
@@ -1,109 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
6
- };
7
-
8
- // src/interfaces/request-plugin.interface.ts
9
- var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
10
- PluginLifecycle2["before"] = "before";
11
- PluginLifecycle2["after"] = "after";
12
- PluginLifecycle2["catch"] = "catch";
13
- return PluginLifecycle2;
14
- })(PluginLifecycle || {});
15
-
16
- // src/request-service.ts
17
- var _RequestService = class {
18
- static getInstance() {
19
- if (this.instance) {
20
- return this.instance;
21
- }
22
- return new _RequestService();
23
- }
24
- getRequestAdapter() {
25
- if (!_RequestService.config.adapter) {
26
- throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
27
- }
28
- return _RequestService.config.adapter;
29
- }
30
- execRequestPlugin(plugins = [], options) {
31
- _RequestService.config.plugins.forEach(
32
- (service) => service.before && service.before(options)
33
- );
34
- plugins.forEach((service) => service.before && service.before(options));
35
- }
36
- execResponsePlugin(leftcycle, plugins = [], options, response) {
37
- plugins.forEach((plugin) => {
38
- const leftcycleFn = plugin[leftcycle];
39
- leftcycleFn && leftcycleFn.bind(plugin)(response, options);
40
- });
41
- _RequestService.config.plugins.forEach((plugin) => {
42
- const leftcycleFn = plugin[leftcycle];
43
- leftcycleFn && leftcycleFn.bind(plugin)(response, options);
44
- });
45
- }
46
- parseRequestPath(path, paramsPath) {
47
- if (paramsPath) {
48
- return Object.entries(paramsPath).reduce(
49
- (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
50
- path
51
- );
52
- } else {
53
- return path;
54
- }
55
- }
56
- startRequest(adapter, options) {
57
- return adapter.request({
58
- baseURL: _RequestService.config.gateway,
59
- pathURL: this.parseRequestPath(options.path, options.paramsPath),
60
- method: options.method,
61
- headers: options.headers || {},
62
- paramsQuery: options.paramsQuery,
63
- paramsBody: options.paramsBody
64
- });
65
- }
66
- execInterceptors(response, hasException = false) {
67
- var _a;
68
- const interceptors = (_a = _RequestService.config) == null ? void 0 : _a.interceptors;
69
- if (!(interceptors == null ? void 0 : interceptors.status) || !(interceptors == null ? void 0 : interceptors.error) || !(interceptors == null ? void 0 : interceptors.success) || !(interceptors == null ? void 0 : interceptors.exception)) {
70
- throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
71
- }
72
- const status = interceptors.status.exec(response) && !hasException;
73
- if (hasException) {
74
- interceptors.exception.exec(response);
75
- }
76
- if (status) {
77
- return Promise.resolve(interceptors.success.exec(response));
78
- } else {
79
- return Promise.reject(interceptors.error.exec(response));
80
- }
81
- }
82
- async send(options, plugins = []) {
83
- if (!_RequestService.config) {
84
- throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
85
- }
86
- let hasException = false;
87
- const adapter = this.getRequestAdapter();
88
- this.execRequestPlugin(plugins, options);
89
- const response = await this.startRequest(adapter, options).then((response2) => adapter.transformResponse(response2)).catch((exception) => {
90
- hasException = true;
91
- return adapter.transformException(exception);
92
- });
93
- if (!hasException) {
94
- this.execResponsePlugin("after" /* after */, plugins, options, response);
95
- } else {
96
- this.execResponsePlugin("catch" /* catch */, plugins, options, response);
97
- }
98
- return this.execInterceptors(response, hasException);
99
- }
100
- };
101
- var RequestService = _RequestService;
102
- __publicField(RequestService, "config");
103
- __publicField(RequestService, "instance");
104
-
105
- export {
106
- __publicField,
107
- PluginLifecycle,
108
- RequestService
109
- };
@@ -1,53 +0,0 @@
1
- /**
2
- * 请求方法类型
3
- */
4
- declare enum RequestMethod {
5
- Get = "GET",
6
- Post = "POST",
7
- Put = "PUT",
8
- Delete = "DELETE",
9
- Options = "OPTIONS",
10
- Head = "HEAD",
11
- Patch = "PATCH"
12
- }
13
- interface RequestSendOptions {
14
- path: string;
15
- method: RequestMethod | string;
16
- headers?: Record<string, string>;
17
- paramsPath?: Record<string, string | number>;
18
- paramsQuery?: Record<string, any>;
19
- paramsBody?: any;
20
- }
21
-
22
- interface RequestAdapter {
23
- /**
24
- * 发送请求
25
- */
26
- request(options: RequestAdapterOptions): Promise<any>;
27
- /**
28
- * 转换Response
29
- * @param any
30
- */
31
- transformResponse(response: any): AdapterResponse;
32
- /**
33
- * 转换Exception
34
- * @param any
35
- */
36
- transformException(response: any): AdapterResponse;
37
- }
38
- interface RequestAdapterOptions {
39
- baseURL: string;
40
- pathURL: string;
41
- headers: Record<string, string>;
42
- method: RequestMethod | string;
43
- paramsQuery?: Record<string, any>;
44
- paramsBody?: any;
45
- }
46
- interface AdapterResponse {
47
- data: Record<string, any>;
48
- status: number;
49
- statusText: string;
50
- headers: Record<string, string | string[] | undefined>;
51
- }
52
-
53
- export { AdapterResponse as A, RequestSendOptions as R, RequestAdapter as a, RequestAdapterOptions as b, RequestMethod as c };