@gopowerteam/request 0.1.20 → 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.mjs ADDED
@@ -0,0 +1,244 @@
1
+ //#region src/interfaces/request-generate.interface.ts
2
+ let RequestGenerateType = /* @__PURE__ */ function(RequestGenerateType) {
3
+ RequestGenerateType["Request"] = "TO_REQUEST";
4
+ RequestGenerateType["URL"] = "TO_URL";
5
+ return RequestGenerateType;
6
+ }({});
7
+
8
+ //#endregion
9
+ //#region src/interfaces/request-plugin.interface.ts
10
+ let PluginLifecycle = /* @__PURE__ */ function(PluginLifecycle) {
11
+ PluginLifecycle["before"] = "before";
12
+ PluginLifecycle["after"] = "after";
13
+ PluginLifecycle["catch"] = "catch";
14
+ return PluginLifecycle;
15
+ }({});
16
+
17
+ //#endregion
18
+ //#region src/interfaces/request-send.interface.ts
19
+ /**
20
+ * 请求方法类型
21
+ */
22
+ let RequestMethod = /* @__PURE__ */ function(RequestMethod) {
23
+ RequestMethod["Get"] = "GET";
24
+ RequestMethod["Post"] = "POST";
25
+ RequestMethod["Put"] = "PUT";
26
+ RequestMethod["Delete"] = "DELETE";
27
+ RequestMethod["Options"] = "OPTIONS";
28
+ RequestMethod["Head"] = "HEAD";
29
+ RequestMethod["Patch"] = "PATCH";
30
+ return RequestMethod;
31
+ }({});
32
+
33
+ //#endregion
34
+ //#region src/utils/query-string.ts
35
+ /**
36
+ * 编码字符串
37
+ */
38
+ function encodeValue(value, encode) {
39
+ if (!encode) return value;
40
+ return encodeURIComponent(value);
41
+ }
42
+ /**
43
+ * 处理嵌套对象的键名
44
+ */
45
+ function getKeyWithDot(key, childKey, allowDots) {
46
+ return allowDots ? `${key}.${childKey}` : `${key}[${childKey}]`;
47
+ }
48
+ /**
49
+ * 递归处理对象值
50
+ */
51
+ function processValue(value, options, parentKey = "") {
52
+ const result = [];
53
+ if (value === null || value === void 0) {
54
+ if (!options.skipNulls) result.push(`${parentKey}=`);
55
+ return result;
56
+ }
57
+ if (Array.isArray(value)) if (options.arrayFormat === "comma") {
58
+ const filteredValues = value.filter((item) => item !== null && item !== void 0);
59
+ if (filteredValues.length > 0) {
60
+ const encodedValue = encodeValue(filteredValues.map((item) => typeof item === "object" ? JSON.stringify(item) : item.toString()).join(","), options.encode !== false);
61
+ result.push(`${parentKey}=${encodedValue}`);
62
+ }
63
+ } else value.forEach((item, index) => {
64
+ let itemKey;
65
+ const shouldEncode = options.encode !== false;
66
+ if (options.arrayFormat === "indices") itemKey = parentKey ? `${parentKey}[${index}]` : `[${index}]`;
67
+ else if (options.arrayFormat === "brackets") itemKey = parentKey ? `${parentKey}[]` : "[]";
68
+ else itemKey = parentKey;
69
+ if (typeof item === "object" && item !== null) result.push(...processValue(item, options, itemKey));
70
+ else {
71
+ const encodedValue = encodeValue(item.toString(), shouldEncode);
72
+ result.push(`${itemKey}=${encodedValue}`);
73
+ }
74
+ });
75
+ else if (typeof value === "object") Object.keys(value).forEach((childKey) => {
76
+ const fullKey = parentKey ? getKeyWithDot(parentKey, childKey, options.allowDots || false) : childKey;
77
+ result.push(...processValue(value[childKey], options, fullKey));
78
+ });
79
+ else {
80
+ const shouldEncode = options.encode !== false;
81
+ const encodedValue = encodeValue(value.toString(), shouldEncode);
82
+ const encodedKey = options.encodeValuesOnly ? parentKey : encodeValue(parentKey, shouldEncode);
83
+ result.push(`${encodedKey}=${encodedValue}`);
84
+ }
85
+ return result;
86
+ }
87
+ /**
88
+ * 将对象序列化为查询字符串
89
+ */
90
+ function stringify(obj, options = {}) {
91
+ const { arrayFormat = "indices", skipNulls = true, allowDots = true, encodeValuesOnly = false, encode = true, addQueryPrefix = false } = options;
92
+ if (!obj || typeof obj !== "object") return options.addQueryPrefix ? "?" : "";
93
+ const parts = [];
94
+ Object.keys(obj).forEach((key) => {
95
+ const value = obj[key];
96
+ const processedValues = processValue(value, {
97
+ arrayFormat,
98
+ skipNulls,
99
+ allowDots,
100
+ encodeValuesOnly,
101
+ encode,
102
+ addQueryPrefix
103
+ }, key);
104
+ parts.push(...processedValues);
105
+ });
106
+ const queryString = parts.join("&");
107
+ return addQueryPrefix ? queryString ? `?${queryString}` : "?" : queryString;
108
+ }
109
+
110
+ //#endregion
111
+ //#region src/request-service.ts
112
+ var RequestService = class RequestService {
113
+ static config;
114
+ static instance;
115
+ /**
116
+ * 获取服务请求单例
117
+ */
118
+ static getInstance() {
119
+ if (this.instance) return this.instance;
120
+ return new RequestService();
121
+ }
122
+ /**
123
+ * 获取RequestAdatper
124
+ * @returns RequestAdapter
125
+ */
126
+ getRequestAdapter() {
127
+ if (!RequestService.config.adapter) throw new Error("请检查是否配置请求Adatper");
128
+ return RequestService.config.adapter;
129
+ }
130
+ /**
131
+ * 执行前置插件逻辑
132
+ * @param plugins
133
+ * @param options
134
+ */
135
+ async execRequestPlugin(plugins = [], options) {
136
+ const extraParams = {};
137
+ const appendParams = (params) => {
138
+ Object.assign(extraParams, params || {});
139
+ };
140
+ for (const plugin of RequestService.config.plugins) if (plugin.before) await plugin.before(options, appendParams);
141
+ for (const plugin of plugins) if (plugin.before) await plugin.before(options, appendParams);
142
+ return extraParams;
143
+ }
144
+ /**
145
+ * 执行前置插件逻辑
146
+ */
147
+ execResponsePlugin(leftcycle, plugins = [], options, response) {
148
+ plugins.forEach((plugin) => {
149
+ const leftcycleFn = plugin[leftcycle];
150
+ if (leftcycleFn) leftcycleFn.bind(plugin)(response, options);
151
+ });
152
+ RequestService.config.plugins.forEach((plugin) => {
153
+ const leftcycleFn = plugin[leftcycle];
154
+ if (leftcycleFn) leftcycleFn.bind(plugin)(response, options);
155
+ });
156
+ }
157
+ /**
158
+ * 转换请求路径
159
+ */
160
+ parseRequestPath(path, paramsPath, service) {
161
+ if (service) path = `/${service}/${path}`.replace(/\/{2,3}/g, "/");
162
+ if (paramsPath) return Object.entries(paramsPath).reduce((r, [key, value]) => r.replace(`{${key}}`, value.toString()), path);
163
+ else return path;
164
+ }
165
+ /**
166
+ * 开始请求
167
+ * @param adapter
168
+ * @param options
169
+ * @returns Promise
170
+ */
171
+ startRequest(adapter, options, extraParams) {
172
+ return adapter.request({
173
+ baseURL: RequestService.config.gateway,
174
+ pathURL: this.parseRequestPath(options.path, options.paramsPath, options.service),
175
+ method: options.method,
176
+ headers: options.headers || {},
177
+ paramsQuery: options.paramsQuery,
178
+ paramsBody: options.paramsBody,
179
+ extraParams
180
+ });
181
+ }
182
+ /**
183
+ * 执行拦截器
184
+ * @param response 请求响应对象
185
+ * @returns Promise
186
+ */
187
+ execInterceptors(response, hasException = false) {
188
+ const interceptors = RequestService.config?.interceptors;
189
+ if (!interceptors?.status || !interceptors?.error || !interceptors?.success || !interceptors?.exception) throw new Error("请检查拦截器配置");
190
+ const status = interceptors.status.exec(response) && !hasException;
191
+ if (hasException) interceptors.exception.exec(response);
192
+ if (status) return Promise.resolve(interceptors.success.exec(response));
193
+ else return Promise.reject(interceptors.error.exec(response));
194
+ }
195
+ /**
196
+ * 发送请求
197
+ * @param {RequestSendOptions} options 请求选项
198
+ * @param {RequestPlugin[]} requestPlugins 请求插件
199
+ * @returns Promise
200
+ */
201
+ async send(options, requestPlugins = []) {
202
+ if (!RequestService.config) throw new Error("请检查请求配置是否完成");
203
+ let hasException = false;
204
+ const adapter = this.getRequestAdapter();
205
+ const plugins = requestPlugins.filter(Boolean);
206
+ const extraParams = await this.execRequestPlugin(plugins, options);
207
+ const response = await this.startRequest(adapter, options, extraParams).then((response) => adapter.transformResponse(response)).catch((exception) => {
208
+ hasException = true;
209
+ return adapter.transformException(exception);
210
+ });
211
+ if (!hasException) this.execResponsePlugin(PluginLifecycle.after, plugins, options, response);
212
+ else this.execResponsePlugin(PluginLifecycle.catch, plugins, options, response);
213
+ return this.execInterceptors(response, hasException);
214
+ }
215
+ /**
216
+ * 生成请求路径
217
+ * @param {RequestSendOptions} options 请求选项
218
+ * @param {RequestPlugin[]} plugins 请求插件
219
+ * @returns string
220
+ */
221
+ toURL(options, plugins = []) {
222
+ if (!RequestService.config) throw new Error("请检查请求配置是否完成");
223
+ if (plugins && plugins.length) this.execRequestPlugin(plugins.filter(Boolean), options);
224
+ return `${RequestService.config.gateway}${this.parseRequestPath(options.path, options.paramsPath, options.service)}${stringify(options.paramsQuery || {}, {
225
+ arrayFormat: "repeat",
226
+ skipNulls: true,
227
+ allowDots: true,
228
+ encodeValuesOnly: true,
229
+ encode: true,
230
+ addQueryPrefix: true,
231
+ ...RequestService.config.qs || {}
232
+ })}`;
233
+ }
234
+ };
235
+
236
+ //#endregion
237
+ //#region src/request-setup.ts
238
+ function setup(config) {
239
+ RequestService.config = config;
240
+ RequestService.config?.adapter?.injectConfig?.(config);
241
+ }
242
+
243
+ //#endregion
244
+ export { PluginLifecycle, RequestGenerateType, RequestMethod, RequestService, setup };
@@ -0,0 +1,103 @@
1
+ import { IStringifyOptions } from "qs";
2
+
3
+ //#region src/interfaces/request-send.interface.d.ts
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
+ service?: string;
18
+ path: string;
19
+ method: RequestMethod | string;
20
+ headers?: Record<string, string>;
21
+ paramsPath?: Record<string, string | number>;
22
+ paramsQuery?: Record<string, any>;
23
+ paramsBody?: any;
24
+ }
25
+ //#endregion
26
+ //#region src/interfaces/request-plugin.interface.d.ts
27
+ /**
28
+ * 请求插件
29
+ */
30
+ interface RequestPlugin {
31
+ before?: (options: RequestSendOptions, appendParams: (params: Record<string, any>) => void) => void | Promise<void>;
32
+ after?: (response: AdapterResponse, options: RequestSendOptions) => void;
33
+ catch?: (response: AdapterResponse, options: RequestSendOptions) => void;
34
+ }
35
+ declare enum PluginLifecycle {
36
+ before = "before",
37
+ after = "after",
38
+ catch = "catch"
39
+ }
40
+ type RequestLifecycle = PluginLifecycle.before;
41
+ type ResponseLifecycle = PluginLifecycle.after | PluginLifecycle.catch;
42
+ //#endregion
43
+ //#region src/interfaces/response-interceptor.interface.d.ts
44
+ interface ResponseInterceptor {
45
+ exec: (response: AdapterResponse) => any;
46
+ }
47
+ //#endregion
48
+ //#region src/interfaces/request-setup.interface.d.ts
49
+ interface RequestSetupConfig {
50
+ gateway: string;
51
+ timeout?: number;
52
+ qs?: IStringifyOptions;
53
+ adapter?: RequestAdapter;
54
+ interceptors: {
55
+ status: ResponseInterceptor;
56
+ success: ResponseInterceptor;
57
+ error: ResponseInterceptor;
58
+ exception: ResponseInterceptor;
59
+ };
60
+ plugins: RequestPlugin[];
61
+ }
62
+ //#endregion
63
+ //#region src/interfaces/request-adapter.interface.d.ts
64
+ interface RequestAdapter {
65
+ /**
66
+ * 注入全局配置文件
67
+ * @param config
68
+ * @returns
69
+ */
70
+ injectConfig?: (config: RequestSetupConfig) => void;
71
+ /**
72
+ * 发送请求
73
+ */
74
+ request: (options: RequestAdapterOptions) => Promise<any>;
75
+ /**
76
+ * 转换Response
77
+ * @param response
78
+ */
79
+ transformResponse: (response: any) => AdapterResponse;
80
+ /**
81
+ * 转换Exception
82
+ * @param response
83
+ */
84
+ transformException: (response: any) => AdapterResponse;
85
+ }
86
+ interface RequestAdapterOptions {
87
+ baseURL: string;
88
+ pathURL: string;
89
+ headers: Record<string, string>;
90
+ method: RequestMethod | string;
91
+ paramsQuery?: Record<string, any>;
92
+ paramsBody?: any;
93
+ extraParams?: any;
94
+ }
95
+ interface AdapterResponse {
96
+ data: Record<string, any>;
97
+ status: number;
98
+ statusText: string;
99
+ headers: AdapterResponseHeaders;
100
+ }
101
+ type AdapterResponseHeaders = Record<string, string | string[] | number | boolean | undefined>;
102
+ //#endregion
103
+ export { RequestSetupConfig as a, RequestLifecycle as c, RequestMethod as d, RequestSendOptions as f, RequestAdapterOptions as i, RequestPlugin as l, AdapterResponseHeaders as n, ResponseInterceptor as o, RequestAdapter as r, PluginLifecycle as s, AdapterResponse as t, ResponseLifecycle as u };
package/package.json CHANGED
@@ -1,47 +1,53 @@
1
1
  {
2
2
  "name": "@gopowerteam/request",
3
- "private": false,
4
- "version": "0.1.20",
5
3
  "type": "module",
6
- "files": [
7
- "dist",
8
- "adapters.d.ts",
9
- "README.md"
10
- ],
4
+ "version": "0.2.0",
5
+ "private": false,
11
6
  "keywords": [
12
7
  "gopowerteam",
13
8
  "request"
14
9
  ],
15
- "main": "./dist/index.cjs",
16
- "module": "./dist/index.js",
17
- "types": "./dist/index.d.ts",
18
10
  "exports": {
19
11
  ".": {
20
- "require": "./dist/index.cjs",
21
- "import": "./dist/index.js",
22
- "types": "./dist/index.d.ts"
12
+ "types": "./dist/index.d.mts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.cjs"
23
15
  },
24
16
  "./adapters": {
25
- "require": "./dist/adapters/index.cjs",
26
- "import": "./dist/adapters/index.js",
27
- "types": "./dist/adapters/index.d.ts"
17
+ "types": "./dist/adapters/index.d.mts",
18
+ "import": "./dist/adapters/index.mjs",
19
+ "require": "./dist/adapters/index.cjs"
28
20
  }
29
21
  },
22
+ "main": "./dist/index.cjs",
23
+ "module": "./dist/index.mjs",
24
+ "types": "./dist/index.d.mts",
25
+ "files": [
26
+ "README.md",
27
+ "adapters.d.ts",
28
+ "dist"
29
+ ],
30
+ "dependencies": {
31
+ "axios": "^1.13.5",
32
+ "qs": "^6.15.0"
33
+ },
30
34
  "devDependencies": {
31
- "@types/jest": "^29.4.0",
32
- "@types/node": "18",
33
- "@types/qs": "^6.9.7",
34
- "jest": "^29.4.3",
35
- "ts-jest": "^29.0.5",
36
- "tsup": "^6.6.3",
37
- "typescript": "^4.9.5"
35
+ "@types/node": "24",
36
+ "@types/qs": "^6.14.0",
37
+ "tsdown": "0.20.3",
38
+ "typescript": "^5.9.3",
39
+ "vitest": "^3.0.0"
38
40
  },
39
- "dependencies": {
40
- "axios": "^1.3.4",
41
- "qs": "^6.11.0"
41
+ "publishConfig": {
42
+ "registry": "https://registry.npmjs.org",
43
+ "access": "public"
42
44
  },
43
45
  "scripts": {
44
- "test": "jest --coverage",
45
- "build": "tsup"
46
+ "dev": "tsdown --watch",
47
+ "test": "vitest run",
48
+ "test:watch": "vitest",
49
+ "test:coverage": "vitest run --coverage",
50
+ "build": "tsdown",
51
+ "lint": "eslint . --fix"
46
52
  }
47
53
  }
@@ -1,33 +0,0 @@
1
- import { c as RequestAdapter, R as RequestSetupConfig, d as RequestAdapterOptions, A as AdapterResponse } from '../request-plugin.interface-3df174bc.js';
2
- import { AxiosResponse, AxiosError } from 'axios';
3
- import 'qs';
4
-
5
- declare class AxiosAdapter implements RequestAdapter {
6
- private static axiosInstance;
7
- private config;
8
- injectConfig(config: RequestSetupConfig): void;
9
- /**
10
- * 获取Axios实例
11
- */
12
- private getAxiosInstance;
13
- /**
14
- * 发送请求
15
- * @param options 请求参数
16
- * @returns AxiosResponse
17
- */
18
- request({ baseURL, pathURL, headers, method, paramsQuery, paramsBody, extraParams }: RequestAdapterOptions): Promise<AxiosResponse<any, any>>;
19
- /**
20
- * 转换Response
21
- * @param response
22
- * @returns
23
- */
24
- transformResponse(response: AxiosResponse): AdapterResponse;
25
- /**
26
- * 转换Response
27
- * @param response
28
- * @returns
29
- */
30
- transformException(exception: AxiosError): AdapterResponse;
31
- }
32
-
33
- export { AxiosAdapter };
@@ -1,97 +0,0 @@
1
- import {
2
- __publicField
3
- } from "../chunk-XXPGZHWZ.js";
4
-
5
- // src/adapters/axios.adapter.ts
6
- import axios from "axios";
7
- import * as qs from "qs";
8
- var _AxiosAdapter = class {
9
- config;
10
- injectConfig(config) {
11
- this.config = config;
12
- }
13
- /**
14
- * 获取Axios实例
15
- */
16
- getAxiosInstance() {
17
- if (!_AxiosAdapter.axiosInstance) {
18
- _AxiosAdapter.axiosInstance = axios.create({
19
- timeout: this.config?.timeout,
20
- headers: {
21
- "Content-Type": "application/json"
22
- },
23
- paramsSerializer: {
24
- serialize: (params) => qs.stringify(
25
- params,
26
- this.config?.qs || {
27
- arrayFormat: "repeat",
28
- skipNulls: true,
29
- allowDots: true,
30
- encodeValuesOnly: true,
31
- encode: true,
32
- sort: (a, b) => a.localeCompare(b),
33
- filter: (_, value) => ["", void 0, null].some((v) => v === value) ? void 0 : value
34
- }
35
- )
36
- }
37
- });
38
- }
39
- return _AxiosAdapter.axiosInstance;
40
- }
41
- /**
42
- * 发送请求
43
- * @param options 请求参数
44
- * @returns AxiosResponse
45
- */
46
- request({
47
- baseURL,
48
- pathURL,
49
- headers,
50
- method,
51
- paramsQuery,
52
- paramsBody,
53
- extraParams = {}
54
- }) {
55
- const axiosInstance = this.getAxiosInstance();
56
- return axiosInstance.request({
57
- method,
58
- baseURL,
59
- headers,
60
- params: paramsQuery,
61
- data: paramsBody,
62
- url: pathURL,
63
- ...extraParams
64
- });
65
- }
66
- /**
67
- * 转换Response
68
- * @param response
69
- * @returns
70
- */
71
- transformResponse(response) {
72
- return {
73
- data: response.data,
74
- statusText: response.statusText,
75
- status: response.status,
76
- headers: response.headers
77
- };
78
- }
79
- /**
80
- * 转换Response
81
- * @param response
82
- * @returns
83
- */
84
- transformException(exception) {
85
- return {
86
- data: exception.response?.data || {},
87
- statusText: exception.response?.statusText || "",
88
- status: exception.response?.status || 400,
89
- headers: exception.response?.headers || {}
90
- };
91
- }
92
- };
93
- var AxiosAdapter = _AxiosAdapter;
94
- __publicField(AxiosAdapter, "axiosInstance");
95
- export {
96
- AxiosAdapter
97
- };
@@ -1,10 +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
- export {
9
- __publicField
10
- };
package/dist/index.d.ts DELETED
@@ -1,72 +0,0 @@
1
- import { R as RequestSetupConfig, a as RequestSendOptions, b as RequestPlugin } from './request-plugin.interface-3df174bc.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-3df174bc.js';
3
- import 'qs';
4
-
5
- declare class RequestService {
6
- static config: RequestSetupConfig;
7
- static instance: RequestService;
8
- /**
9
- * 获取服务请求单例
10
- */
11
- static getInstance(): RequestService;
12
- /**
13
- * 获取RequestAdatper
14
- * @returns
15
- */
16
- private getRequestAdapter;
17
- /**
18
- * 执行前置插件逻辑
19
- * @param plugins
20
- * @param options
21
- */
22
- private execRequestPlugin;
23
- /**
24
- * 执行前置插件逻辑
25
- * @param plugins
26
- * @param options
27
- */
28
- private execResponsePlugin;
29
- /**
30
- * 转换请求路径
31
- */
32
- private parseRequestPath;
33
- /**
34
- * 开始请求
35
- * @param adapter
36
- * @param options
37
- * @returns
38
- */
39
- private startRequest;
40
- /**
41
- * 执行拦截器
42
- * @param response 请求响应对象
43
- * @returns
44
- */
45
- private execInterceptors;
46
- /**
47
- * 发送请求
48
- * @param {RequestSendOptions} options 请求选项
49
- * @param {RequestPlugin[]} plugins 请求插件
50
- * @returns
51
- */
52
- send(options: RequestSendOptions, requestPlugins?: (RequestPlugin | undefined)[]): Promise<any>;
53
- /**
54
- * 生成请求路径
55
- * @param {RequestSendOptions} options 请求选项
56
- * @param {RequestPlugin[]} plugins 请求插件
57
- * @returns
58
- */
59
- toURL(options: RequestSendOptions, plugins?: (RequestPlugin | undefined)[]): string;
60
- }
61
-
62
- declare function setup(config: RequestSetupConfig): void;
63
-
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 };