@gopowerteam/request 0.1.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.cjs ADDED
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __publicField = (obj, key, value) => {
27
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ return value;
29
+ };
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ AxiosAdapter: () => AxiosAdapter,
35
+ PluginLifecycle: () => PluginLifecycle,
36
+ RequestMethod: () => RequestMethod,
37
+ RequestService: () => RequestService,
38
+ setup: () => setup
39
+ });
40
+ module.exports = __toCommonJS(src_exports);
41
+
42
+ // src/adapters/axios.adapter.ts
43
+ var import_axios = __toESM(require("axios"), 1);
44
+ var _AxiosAdapter = class {
45
+ getAxiosInstance() {
46
+ if (!_AxiosAdapter.axiosInstance) {
47
+ _AxiosAdapter.axiosInstance = import_axios.default.create({
48
+ timeout: RequestService.config.timeout,
49
+ headers: {
50
+ "Content-Type": "application/json"
51
+ }
52
+ });
53
+ }
54
+ return _AxiosAdapter.axiosInstance;
55
+ }
56
+ request({
57
+ baseURL,
58
+ pathURL,
59
+ headers,
60
+ method,
61
+ paramsQuery,
62
+ paramsBody
63
+ }) {
64
+ const axiosInstance = this.getAxiosInstance();
65
+ return axiosInstance.request({
66
+ method,
67
+ baseURL,
68
+ headers,
69
+ params: paramsQuery,
70
+ data: paramsBody,
71
+ url: pathURL
72
+ });
73
+ }
74
+ transformResponse(response) {
75
+ return {
76
+ data: response.data,
77
+ statusText: response.statusText,
78
+ status: response.status,
79
+ headers: response.headers
80
+ };
81
+ }
82
+ };
83
+ var AxiosAdapter = _AxiosAdapter;
84
+ __publicField(AxiosAdapter, "axiosInstance");
85
+
86
+ // src/interfaces/request-plugin.interface.ts
87
+ var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
88
+ PluginLifecycle2["before"] = "before";
89
+ PluginLifecycle2["after"] = "after";
90
+ PluginLifecycle2["catch"] = "catch";
91
+ return PluginLifecycle2;
92
+ })(PluginLifecycle || {});
93
+
94
+ // src/request-service.ts
95
+ var _RequestService = class {
96
+ static getInstance() {
97
+ if (this.instance) {
98
+ return this.instance;
99
+ }
100
+ return new _RequestService();
101
+ }
102
+ getRequestAdapter() {
103
+ if (typeof _RequestService.config.adapter === "string") {
104
+ switch (_RequestService.config.adapter) {
105
+ case "axios":
106
+ return new AxiosAdapter();
107
+ }
108
+ }
109
+ if (!_RequestService.config.adapter) {
110
+ throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
111
+ }
112
+ return _RequestService.config.adapter;
113
+ }
114
+ execRequestPlugin(plugins = [], options) {
115
+ _RequestService.config.plugins.forEach(
116
+ (service) => service.before && service.before(options)
117
+ );
118
+ plugins.forEach((service) => service.before && service.before(options));
119
+ }
120
+ execResponsePlugin(leftcycle, plugins = [], options, response) {
121
+ plugins.forEach(
122
+ (plugin) => plugin[leftcycle] && plugin[leftcycle](response, options)
123
+ );
124
+ _RequestService.config.plugins.forEach(
125
+ (plugin) => plugin[leftcycle] && plugin[leftcycle](response, options)
126
+ );
127
+ }
128
+ parseRequestPath(path, paramsPath) {
129
+ if (paramsPath) {
130
+ return Object.entries(paramsPath).reduce(
131
+ (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
132
+ path
133
+ );
134
+ } else {
135
+ return path;
136
+ }
137
+ }
138
+ startRequest(adapter, options) {
139
+ return adapter.request({
140
+ baseURL: _RequestService.config.gateway,
141
+ pathURL: this.parseRequestPath(options.path, options.paramsPath),
142
+ method: options.method,
143
+ headers: options.headers || {},
144
+ paramsQuery: options.paramsQuery,
145
+ paramsBody: options.paramsBody
146
+ });
147
+ }
148
+ execInterceptors(response, hasException = false) {
149
+ var _a;
150
+ const interceptors = (_a = _RequestService.config) == null ? void 0 : _a.interceptors;
151
+ 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)) {
152
+ throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
153
+ }
154
+ const status = interceptors.status.exec(response) && !hasException;
155
+ if (hasException) {
156
+ interceptors.exception.exec(response);
157
+ }
158
+ if (status) {
159
+ return Promise.resolve(interceptors.success.exec(response));
160
+ } else {
161
+ return Promise.reject(interceptors.error.exec(response));
162
+ }
163
+ }
164
+ async send(options, plugins = []) {
165
+ if (!_RequestService.config) {
166
+ throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
167
+ }
168
+ let hasException = false;
169
+ const adapter = this.getRequestAdapter();
170
+ this.execRequestPlugin(plugins, options);
171
+ const response = await this.startRequest(adapter, options).catch((...response2) => {
172
+ hasException = true;
173
+ return response2;
174
+ }).then((response2) => adapter.transformResponse(response2));
175
+ if (!hasException) {
176
+ this.execResponsePlugin("after" /* after */, plugins, options, response);
177
+ } else {
178
+ this.execResponsePlugin("catch" /* catch */, plugins, options, response);
179
+ }
180
+ return this.execInterceptors(response, hasException);
181
+ }
182
+ };
183
+ var RequestService = _RequestService;
184
+ __publicField(RequestService, "config");
185
+ __publicField(RequestService, "instance");
186
+
187
+ // src/request-setup.ts
188
+ function setup(config) {
189
+ RequestService.config = config;
190
+ }
191
+
192
+ // src/interfaces/request-send.interface.ts
193
+ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
194
+ RequestMethod2["Get"] = "GET";
195
+ RequestMethod2["Post"] = "POST";
196
+ RequestMethod2["Put"] = "PUT";
197
+ RequestMethod2["Delete"] = "DELETE";
198
+ RequestMethod2["Options"] = "OPTIONS";
199
+ RequestMethod2["Head"] = "HEAD";
200
+ RequestMethod2["Patch"] = "PATCH";
201
+ return RequestMethod2;
202
+ })(RequestMethod || {});
203
+ // Annotate the CommonJS export names for ESM import in node:
204
+ 0 && (module.exports = {
205
+ AxiosAdapter,
206
+ PluginLifecycle,
207
+ RequestMethod,
208
+ RequestService,
209
+ setup
210
+ });
@@ -0,0 +1,161 @@
1
+ import { IStringifyOptions } from 'qs';
2
+ import * as axios from 'axios';
3
+
4
+ /**
5
+ * 请求方法类型
6
+ */
7
+ declare enum RequestMethod {
8
+ Get = "GET",
9
+ Post = "POST",
10
+ Put = "PUT",
11
+ Delete = "DELETE",
12
+ Options = "OPTIONS",
13
+ Head = "HEAD",
14
+ Patch = "PATCH"
15
+ }
16
+ interface RequestSendOptions {
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 RequestAdapter {
26
+ /**
27
+ * 发送请求
28
+ */
29
+ request(options: RequestAdapterOptions): Promise<any>;
30
+ /**
31
+ * 转换Response
32
+ * @param any
33
+ */
34
+ transformResponse(response: any): AdapterResponse;
35
+ }
36
+ interface RequestAdapterOptions {
37
+ baseURL: string;
38
+ pathURL: string;
39
+ headers: Record<string, string>;
40
+ method: RequestMethod | string;
41
+ paramsQuery?: Record<string, any>;
42
+ paramsBody?: any;
43
+ }
44
+ interface AdapterResponse {
45
+ data: Record<string, any>;
46
+ status: number;
47
+ statusText: string;
48
+ headers: Record<string, string>;
49
+ }
50
+
51
+ /**
52
+ * 请求插件
53
+ */
54
+ interface RequestPlugin {
55
+ before: (options: RequestSendOptions) => void;
56
+ after: (response: AdapterResponse, options: RequestSendOptions) => void;
57
+ catch: (response: AdapterResponse, options: RequestSendOptions) => void;
58
+ }
59
+ declare enum PluginLifecycle {
60
+ before = "before",
61
+ after = "after",
62
+ catch = "catch"
63
+ }
64
+ declare type RequestLifecycle = PluginLifecycle.before;
65
+ declare type ResponseLifecycle = PluginLifecycle.after | PluginLifecycle.catch;
66
+
67
+ interface ResponseInterceptor {
68
+ exec(response: AdapterResponse): any;
69
+ }
70
+
71
+ /**
72
+ * 内部支持适配器
73
+ */
74
+ declare type InternalAdapter = 'axios';
75
+ interface RequestSetupConfig {
76
+ gateway: string;
77
+ timeout?: number;
78
+ qs?: IStringifyOptions;
79
+ adapter?: InternalAdapter | RequestAdapter;
80
+ interceptors: {
81
+ status: ResponseInterceptor;
82
+ success: ResponseInterceptor;
83
+ error: ResponseInterceptor;
84
+ exception: ResponseInterceptor;
85
+ };
86
+ plugins: RequestPlugin[];
87
+ }
88
+
89
+ declare class RequestService {
90
+ static config: RequestSetupConfig;
91
+ static instance: RequestService;
92
+ /**
93
+ * 获取服务请求单例
94
+ */
95
+ static getInstance(): RequestService;
96
+ /**
97
+ * 获取RequestAdatper
98
+ * @returns
99
+ */
100
+ private getRequestAdapter;
101
+ /**
102
+ * 执行前置插件逻辑
103
+ * @param plugins
104
+ * @param options
105
+ */
106
+ private execRequestPlugin;
107
+ /**
108
+ * 执行前置插件逻辑
109
+ * @param plugins
110
+ * @param options
111
+ */
112
+ private execResponsePlugin;
113
+ /**
114
+ * 转换请求路径
115
+ */
116
+ private parseRequestPath;
117
+ /**
118
+ * 开始请求
119
+ * @param adapter
120
+ * @param options
121
+ * @returns
122
+ */
123
+ private startRequest;
124
+ /**
125
+ * 执行拦截器
126
+ * @param response 请求响应对象
127
+ * @returns
128
+ */
129
+ private execInterceptors;
130
+ /**
131
+ * 发送请求
132
+ * @param {RequestSendOptions} options 请求选项
133
+ * @param {RequestPlugin[]} plugins 请求插件
134
+ * @returns
135
+ */
136
+ send(options: RequestSendOptions, plugins?: RequestPlugin[]): Promise<any>;
137
+ }
138
+
139
+ declare function setup(config: RequestSetupConfig): void;
140
+
141
+ declare class AxiosAdapter implements RequestAdapter {
142
+ private static axiosInstance;
143
+ /**
144
+ * 获取Axios实例
145
+ */
146
+ private getAxiosInstance;
147
+ /**
148
+ * 发送请求
149
+ * @param options 请求参数
150
+ * @returns AxiosResponse
151
+ */
152
+ request({ baseURL, pathURL, headers, method, paramsQuery, paramsBody }: RequestAdapterOptions): Promise<axios.AxiosResponse<any, any>>;
153
+ /**
154
+ * 转换Response
155
+ * @param response
156
+ * @returns
157
+ */
158
+ transformResponse(response: any): AdapterResponse;
159
+ }
160
+
161
+ export { AdapterResponse, AxiosAdapter, PluginLifecycle, RequestAdapter, RequestAdapterOptions, RequestLifecycle, RequestMethod, RequestPlugin, RequestSendOptions, RequestService, RequestSetupConfig, ResponseInterceptor, ResponseLifecycle, setup };
package/dist/index.js ADDED
@@ -0,0 +1,175 @@
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/adapters/axios.adapter.ts
9
+ import axios from "axios";
10
+ var _AxiosAdapter = class {
11
+ getAxiosInstance() {
12
+ if (!_AxiosAdapter.axiosInstance) {
13
+ _AxiosAdapter.axiosInstance = axios.create({
14
+ timeout: RequestService.config.timeout,
15
+ headers: {
16
+ "Content-Type": "application/json"
17
+ }
18
+ });
19
+ }
20
+ return _AxiosAdapter.axiosInstance;
21
+ }
22
+ request({
23
+ baseURL,
24
+ pathURL,
25
+ headers,
26
+ method,
27
+ paramsQuery,
28
+ paramsBody
29
+ }) {
30
+ const axiosInstance = this.getAxiosInstance();
31
+ return axiosInstance.request({
32
+ method,
33
+ baseURL,
34
+ headers,
35
+ params: paramsQuery,
36
+ data: paramsBody,
37
+ url: pathURL
38
+ });
39
+ }
40
+ transformResponse(response) {
41
+ return {
42
+ data: response.data,
43
+ statusText: response.statusText,
44
+ status: response.status,
45
+ headers: response.headers
46
+ };
47
+ }
48
+ };
49
+ var AxiosAdapter = _AxiosAdapter;
50
+ __publicField(AxiosAdapter, "axiosInstance");
51
+
52
+ // src/interfaces/request-plugin.interface.ts
53
+ var PluginLifecycle = /* @__PURE__ */ ((PluginLifecycle2) => {
54
+ PluginLifecycle2["before"] = "before";
55
+ PluginLifecycle2["after"] = "after";
56
+ PluginLifecycle2["catch"] = "catch";
57
+ return PluginLifecycle2;
58
+ })(PluginLifecycle || {});
59
+
60
+ // src/request-service.ts
61
+ var _RequestService = class {
62
+ static getInstance() {
63
+ if (this.instance) {
64
+ return this.instance;
65
+ }
66
+ return new _RequestService();
67
+ }
68
+ getRequestAdapter() {
69
+ if (typeof _RequestService.config.adapter === "string") {
70
+ switch (_RequestService.config.adapter) {
71
+ case "axios":
72
+ return new AxiosAdapter();
73
+ }
74
+ }
75
+ if (!_RequestService.config.adapter) {
76
+ throw new Error("\u8BF7\u68C0\u67E5\u662F\u5426\u914D\u7F6E\u8BF7\u6C42Adatper");
77
+ }
78
+ return _RequestService.config.adapter;
79
+ }
80
+ execRequestPlugin(plugins = [], options) {
81
+ _RequestService.config.plugins.forEach(
82
+ (service) => service.before && service.before(options)
83
+ );
84
+ plugins.forEach((service) => service.before && service.before(options));
85
+ }
86
+ execResponsePlugin(leftcycle, plugins = [], options, response) {
87
+ plugins.forEach(
88
+ (plugin) => plugin[leftcycle] && plugin[leftcycle](response, options)
89
+ );
90
+ _RequestService.config.plugins.forEach(
91
+ (plugin) => plugin[leftcycle] && plugin[leftcycle](response, options)
92
+ );
93
+ }
94
+ parseRequestPath(path, paramsPath) {
95
+ if (paramsPath) {
96
+ return Object.entries(paramsPath).reduce(
97
+ (r, [key, value]) => r.replace(`{${key}}`, value.toString()),
98
+ path
99
+ );
100
+ } else {
101
+ return path;
102
+ }
103
+ }
104
+ startRequest(adapter, options) {
105
+ return adapter.request({
106
+ baseURL: _RequestService.config.gateway,
107
+ pathURL: this.parseRequestPath(options.path, options.paramsPath),
108
+ method: options.method,
109
+ headers: options.headers || {},
110
+ paramsQuery: options.paramsQuery,
111
+ paramsBody: options.paramsBody
112
+ });
113
+ }
114
+ execInterceptors(response, hasException = false) {
115
+ var _a;
116
+ const interceptors = (_a = _RequestService.config) == null ? void 0 : _a.interceptors;
117
+ 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)) {
118
+ throw new Error("\u8BF7\u68C0\u67E5\u62E6\u622A\u5668\u914D\u7F6E");
119
+ }
120
+ const status = interceptors.status.exec(response) && !hasException;
121
+ if (hasException) {
122
+ interceptors.exception.exec(response);
123
+ }
124
+ if (status) {
125
+ return Promise.resolve(interceptors.success.exec(response));
126
+ } else {
127
+ return Promise.reject(interceptors.error.exec(response));
128
+ }
129
+ }
130
+ async send(options, plugins = []) {
131
+ if (!_RequestService.config) {
132
+ throw new Error("\u8BF7\u68C0\u67E5\u8BF7\u6C42\u914D\u7F6E\u662F\u5426\u5B8C\u6210");
133
+ }
134
+ let hasException = false;
135
+ const adapter = this.getRequestAdapter();
136
+ this.execRequestPlugin(plugins, options);
137
+ const response = await this.startRequest(adapter, options).catch((...response2) => {
138
+ hasException = true;
139
+ return response2;
140
+ }).then((response2) => adapter.transformResponse(response2));
141
+ if (!hasException) {
142
+ this.execResponsePlugin("after" /* after */, plugins, options, response);
143
+ } else {
144
+ this.execResponsePlugin("catch" /* catch */, plugins, options, response);
145
+ }
146
+ return this.execInterceptors(response, hasException);
147
+ }
148
+ };
149
+ var RequestService = _RequestService;
150
+ __publicField(RequestService, "config");
151
+ __publicField(RequestService, "instance");
152
+
153
+ // src/request-setup.ts
154
+ function setup(config) {
155
+ RequestService.config = config;
156
+ }
157
+
158
+ // src/interfaces/request-send.interface.ts
159
+ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
160
+ RequestMethod2["Get"] = "GET";
161
+ RequestMethod2["Post"] = "POST";
162
+ RequestMethod2["Put"] = "PUT";
163
+ RequestMethod2["Delete"] = "DELETE";
164
+ RequestMethod2["Options"] = "OPTIONS";
165
+ RequestMethod2["Head"] = "HEAD";
166
+ RequestMethod2["Patch"] = "PATCH";
167
+ return RequestMethod2;
168
+ })(RequestMethod || {});
169
+ export {
170
+ AxiosAdapter,
171
+ PluginLifecycle,
172
+ RequestMethod,
173
+ RequestService,
174
+ setup
175
+ };
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@gopowerteam/request",
3
+ "private": false,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "README.md"
9
+ ],
10
+ "keywords": [
11
+ "gopowerteam",
12
+ "request"
13
+ ],
14
+ "scripts": {
15
+ "test": "jest --coverage",
16
+ "build": "tsup"
17
+ },
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "devDependencies": {
22
+ "@types/axios": "^0.14.0",
23
+ "@types/jest": "^29.1.2",
24
+ "@types/node": "16",
25
+ "@types/qs": "^6.9.7",
26
+ "jest": "^29.1.2",
27
+ "ts-jest": "^29.0.3",
28
+ "ts-node": "^10.9.1",
29
+ "tsup": "^6.2.3",
30
+ "typescript": "^4.8.4"
31
+ },
32
+ "dependencies": {
33
+ "axios": "^1.1.2",
34
+ "qs": "^6.11.0"
35
+ }
36
+ }