@ahoo-wang/fetcher 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # fetcher-core
2
+
3
+ Fetcher-core 是一个基于现代 Fetch API 的 HTTP 客户端库,旨在简化和优化与后端 RESTful API 的交互。它提供了类似于 Axios 的 API,支持路径参数、查询参数、超时设置以及请求和响应拦截器。
4
+
5
+ ## 特性
6
+
7
+ - **兼容 Fetch API**: fetcher 的 API 完全兼容原生 Fetch API,易于上手。
8
+ - **路径和查询参数**: 支持在请求中使用路径参数和查询参数,路径参数使用 `{}` 包裹。
9
+ - **超时设置**: 可以为请求设置超时时间。
10
+ - **请求拦截器**: 支持在请求发送前对请求进行修改。
11
+ - **响应拦截器**: 支持在响应返回后对响应进行处理。
12
+ - **模块化设计**: 代码结构清晰,易于维护和扩展。
13
+
14
+ ## 安装
15
+
16
+ 使用 pnpm 安装:
17
+
18
+ ```bash
19
+ pnpm add @fetcher/core
20
+ ```
21
+
22
+ ## 使用示例
23
+
24
+ ```typescript
25
+ import { Fetcher } from '@fetcher/core';
26
+
27
+ const fetcher = new Fetcher({
28
+ baseURL: 'https://api.example.com',
29
+ timeout: 5000,
30
+ });
31
+
32
+ fetcher
33
+ .get('/users/{id}', { pathParams: { id: 123 } })
34
+ .then(response => {
35
+ console.log(response.data);
36
+ })
37
+ .catch(error => {
38
+ console.error(error);
39
+ });
40
+ ```
41
+
42
+ ## API 参考
43
+
44
+ ### Fetcher
45
+
46
+ - `fetch(url: string, request?: FetcherRequest): Promise<Response>`
47
+ - `get(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>`
48
+ - `post(url: string, request?: Omit<FetcherRequest, 'method'>): Promise<Response>`
49
+ - `put(url: string, request?: Omit<FetcherRequest, 'method'>): Promise<Response>`
50
+ - `delete(url: string, request?: Omit<FetcherRequest, 'method'>): Promise<Response>`
51
+ - `patch(url: string, request?: Omit<FetcherRequest, 'method'>): Promise<Response>`
52
+ - `head(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>`
53
+ - `options(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>`
54
+
55
+ ### UrlBuilder
56
+
57
+ - `build(path: string, pathParams?: Record<string, any>, queryParams?: Record<string, any>): string`
58
+
59
+ ### InterceptorManager
60
+
61
+ - `use(interceptor: T): number`
62
+ - `eject(index: number): void`
63
+ - `clear(): void`
64
+ - `intercept(data: R): Promise<R>`
65
+
66
+ ### FetcherInterceptors
67
+
68
+ - `request: RequestInterceptorManager`
69
+ - `response: ResponseInterceptorManager`
70
+ - `error: ErrorInterceptorManager`
71
+
72
+ #### 使用示例
73
+
74
+ ```typescript
75
+ import { Fetcher } from '@fetcher/core';
76
+
77
+ const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
78
+
79
+ // 添加请求拦截器
80
+ const requestInterceptorId = fetcher.interceptors.request.use({
81
+ intercept(request) {
82
+ // 修改请求配置
83
+ return {
84
+ ...request,
85
+ headers: {
86
+ ...request.headers,
87
+ Authorization: 'Bearer token',
88
+ },
89
+ };
90
+ },
91
+ });
92
+
93
+ // 添加响应拦截器
94
+ const responseInterceptorId = fetcher.interceptors.response.use({
95
+ intercept(response) {
96
+ // 处理响应数据
97
+ return response;
98
+ },
99
+ });
100
+
101
+ // 移除拦截器
102
+ fetcher.interceptors.request.eject(requestInterceptorId);
103
+ fetcher.interceptors.response.eject(responseInterceptorId);
104
+
105
+ // 清空所有拦截器
106
+ fetcher.interceptors.request.clear();
107
+ fetcher.interceptors.response.clear();
108
+ fetcher.interceptors.error.clear();
109
+ ```
110
+
111
+ ## 贡献
112
+
113
+ 欢迎任何形式的贡献!请查看 [贡献指南](https://github.com/Ahoo-Wang/fetcher/blob/main/CONTRIBUTING.md) 了解更多信息。
114
+
115
+ ## 许可证
116
+
117
+ 本项目采用 [Apache-2.0](https://opensource.org/licenses/Apache-2.0) 许可证。
@@ -0,0 +1,115 @@
1
+ import { TimeoutCapable } from './timeout';
2
+ import { BaseURLCapable, HeadersCapable, RequestField } from './types';
3
+ import { FetcherInterceptors } from './interceptor';
4
+ /**
5
+ * Fetcher配置选项接口
6
+ */
7
+ export interface FetcherOptions extends BaseURLCapable, HeadersCapable, TimeoutCapable {
8
+ }
9
+ /**
10
+ * Fetcher请求选项接口
11
+ */
12
+ export interface FetcherRequest extends TimeoutCapable, RequestInit {
13
+ pathParams?: Record<string, any>;
14
+ queryParams?: Record<string, any>;
15
+ }
16
+ /**
17
+ * HTTP请求客户端类,支持URL构建、超时控制等功能
18
+ *
19
+ * @example
20
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
21
+ * const response = await fetcher.fetch('/users/{id}', {
22
+ * pathParams: { id: 123 },
23
+ * queryParams: { filter: 'active' },
24
+ * timeout: 5000
25
+ * });
26
+ */
27
+ export declare class Fetcher implements HeadersCapable, TimeoutCapable {
28
+ headers?: Record<string, string>;
29
+ timeout?: number;
30
+ private urlBuilder;
31
+ interceptors: FetcherInterceptors;
32
+ /**
33
+ * 创建Fetcher实例
34
+ *
35
+ * @param options - Fetcher配置选项
36
+ */
37
+ constructor(options?: FetcherOptions);
38
+ /**
39
+ * 发起HTTP请求
40
+ *
41
+ * @param url - 请求URL路径
42
+ * @param request - 请求选项,包括路径参数、查询参数等
43
+ * @returns Promise<Response> HTTP响应
44
+ */
45
+ fetch(url: string, request?: FetcherRequest): Promise<Response>;
46
+ /**
47
+ * 带超时控制的HTTP请求方法
48
+ *
49
+ * 该方法使用Promise.race来实现超时控制,同时发起fetch请求和超时Promise,
50
+ * 当任一Promise完成时,会返回其结果或抛出异常。
51
+ *
52
+ * @param url - 请求的URL地址
53
+ * @param request - 请求选项,包括method、headers、body等fetch API支持的选项
54
+ * @returns Promise<Response> HTTP响应Promise
55
+ * @throws FetchTimeoutError 当请求超时时抛出
56
+ */
57
+ private timeoutFetch;
58
+ /**
59
+ * 发起GET请求
60
+ *
61
+ * @param url - 请求URL路径
62
+ * @param request - 请求选项,包括路径参数、查询参数等
63
+ * @returns Promise<Response> HTTP响应
64
+ */
65
+ get(url: string, request?: Omit<FetcherRequest, RequestField.METHOD | RequestField.BODY>): Promise<Response>;
66
+ /**
67
+ * 发起POST请求
68
+ *
69
+ * @param url - 请求URL路径
70
+ * @param request - 请求选项,包括路径参数、查询参数、请求体等
71
+ * @returns Promise<Response> HTTP响应
72
+ */
73
+ post(url: string, request?: Omit<FetcherRequest, RequestField.METHOD>): Promise<Response>;
74
+ /**
75
+ * 发起PUT请求
76
+ *
77
+ * @param url - 请求URL路径
78
+ * @param request - 请求选项,包括路径参数、查询参数、请求体等
79
+ * @returns Promise<Response> HTTP响应
80
+ */
81
+ put(url: string, request?: Omit<FetcherRequest, RequestField.METHOD>): Promise<Response>;
82
+ /**
83
+ * 发起DELETE请求
84
+ *
85
+ * @param url - 请求URL路径
86
+ * @param request - 请求选项,包括路径参数、查询参数等
87
+ * @returns Promise<Response> HTTP响应
88
+ */
89
+ delete(url: string, request?: Omit<FetcherRequest, RequestField.METHOD>): Promise<Response>;
90
+ /**
91
+ * 发起PATCH请求
92
+ *
93
+ * @param url - 请求URL路径
94
+ * @param request - 请求选项,包括路径参数、查询参数、请求体等
95
+ * @returns Promise<Response> HTTP响应
96
+ */
97
+ patch(url: string, request?: Omit<FetcherRequest, RequestField.METHOD>): Promise<Response>;
98
+ /**
99
+ * 发起HEAD请求
100
+ *
101
+ * @param url - 请求URL路径
102
+ * @param request - 请求选项,包括路径参数、查询参数等
103
+ * @returns Promise<Response> HTTP响应
104
+ */
105
+ head(url: string, request?: Omit<FetcherRequest, RequestField.METHOD | RequestField.BODY>): Promise<Response>;
106
+ /**
107
+ * 发起OPTIONS请求
108
+ *
109
+ * @param url - 请求URL路径
110
+ * @param request - 请求选项,包括路径参数、查询参数等
111
+ * @returns Promise<Response> HTTP响应
112
+ */
113
+ options(url: string, request?: Omit<FetcherRequest, RequestField.METHOD | RequestField.BODY>): Promise<Response>;
114
+ }
115
+ //# sourceMappingURL=fetcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetcher.d.ts","sourceRoot":"","sources":["../src/fetcher.ts"],"names":[],"mappings":"AACA,OAAO,EAAqC,cAAc,EAAE,MAAM,WAAW,CAAC;AAC9E,OAAO,EACL,cAAc,EACd,cAAc,EAEd,YAAY,EACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,cACf,SAAQ,cAAc,EACpB,cAAc,EACd,cAAc;CAAG;AAMrB;;GAEG;AACH,MAAM,WAAW,cAAe,SAAQ,cAAc,EAAE,WAAW;IACjE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CACnC;AAED;;;;;;;;;;GAUG;AACH,qBAAa,OAAQ,YAAW,cAAc,EAAE,cAAc;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,UAAU,CAAa;IAC/B,YAAY,EAAE,mBAAmB,CAA6B;IAE9D;;;;OAIG;gBACS,OAAO,GAAE,cAA+B;IAMpD;;;;;;OAMG;IACG,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAoCzE;;;;;;;;;;OAUG;YACW,YAAY;IA+B1B;;;;;;OAMG;IACG,GAAG,CACP,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,GAAG,YAAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;IAOpB;;;;;;OAMG;IACG,IAAI,CACR,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAOpB;;;;;;OAMG;IACG,GAAG,CACP,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAOpB;;;;;;OAMG;IACG,MAAM,CACV,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAOpB;;;;;;OAMG;IACG,KAAK,CACT,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,CAAM,GACtD,OAAO,CAAC,QAAQ,CAAC;IAOpB;;;;;;OAMG;IACG,IAAI,CACR,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,GAAG,YAAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;IAOpB;;;;;;OAMG;IACG,OAAO,CACX,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,GAAG,YAAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;CAMrB"}
@@ -0,0 +1,6 @@
1
+ export * from './fetcher';
2
+ export * from './timeout';
3
+ export * from './types';
4
+ export * from './urlBuilder';
5
+ export * from './urls';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC"}
@@ -0,0 +1,276 @@
1
+ function f(r) {
2
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(r);
3
+ }
4
+ function p(r, t) {
5
+ return f(t) ? t : t ? r.replace(/\/?\/$/, "") + "/" + t.replace(/^\/+/, "") : r;
6
+ }
7
+ class m {
8
+ /**
9
+ * 创建UrlBuilder实例
10
+ *
11
+ * @param baseURL - 基础URL,所有构建的URL都将基于此URL
12
+ */
13
+ constructor(t) {
14
+ this.baseURL = t;
15
+ }
16
+ /**
17
+ * 构建完整的URL,包括路径参数替换和查询参数添加
18
+ *
19
+ * @param url - 需要构建的URL路径
20
+ * @param pathParams - 路径参数对象,用于替换URL中的占位符(如{id})
21
+ * @param queryParams - 查询参数对象,将被添加到URL查询字符串中
22
+ * @returns 完整的URL字符串
23
+ * @throws 当路径参数中缺少必需的占位符时抛出错误
24
+ */
25
+ build(t, e, s) {
26
+ let n = p(this.baseURL, t), o = this.interpolateUrl(n, e);
27
+ if (s) {
28
+ const i = new URLSearchParams(s).toString();
29
+ i && (o += "?" + i);
30
+ }
31
+ return o;
32
+ }
33
+ /**
34
+ * 替换url中的占位符参数
35
+ *
36
+ * @param url - 包含占位符的路径字符串,如 "http://localhost/users/{id}/posts/{postId}"
37
+ * @param pathParams - 路径参数对象,用于替换路径中的占位符
38
+ * @returns 替换占位符后的路径字符串
39
+ * @throws 当路径参数中缺少必需的占位符时抛出错误
40
+ */
41
+ interpolateUrl(t, e) {
42
+ return e ? t.replace(/{([^}]+)}/g, (s, n) => {
43
+ const o = e[n];
44
+ if (o === void 0)
45
+ throw new Error(`Missing required path parameter: ${n}`);
46
+ return String(o);
47
+ }) : t;
48
+ }
49
+ }
50
+ function d(r, t) {
51
+ return typeof r < "u" ? r : t;
52
+ }
53
+ class a extends Error {
54
+ constructor(t, e, s) {
55
+ const n = `Request timeout of ${s}ms exceeded for ${e?.method || "GET"} ${t}`;
56
+ super(n), this.name = "FetchTimeoutError", this.url = t, this.request = e, Object.setPrototypeOf(this, a.prototype);
57
+ }
58
+ }
59
+ var c = /* @__PURE__ */ ((r) => (r.GET = "GET", r.POST = "POST", r.PUT = "PUT", r.DELETE = "DELETE", r.PATCH = "PATCH", r.HEAD = "HEAD", r.OPTIONS = "OPTIONS", r))(c || {}), T = /* @__PURE__ */ ((r) => (r.METHOD = "method", r.BODY = "body", r))(T || {});
60
+ class h {
61
+ constructor() {
62
+ this.interceptors = [];
63
+ }
64
+ /**
65
+ * 添加拦截器到管理器中
66
+ * @param interceptor - 要添加的拦截器
67
+ * @returns 拦截器在管理器中的索引位置
68
+ */
69
+ use(t) {
70
+ const e = this.interceptors.length;
71
+ return this.interceptors.push(t), e;
72
+ }
73
+ /**
74
+ * 根据索引移除拦截器
75
+ * @param index - 要移除的拦截器索引
76
+ */
77
+ eject(t) {
78
+ this.interceptors[t] && (this.interceptors[t] = null);
79
+ }
80
+ /**
81
+ * 清空所有拦截器
82
+ */
83
+ clear() {
84
+ this.interceptors = [];
85
+ }
86
+ /**
87
+ * 依次执行所有拦截器对数据的处理
88
+ * @param data - 需要处理的数据
89
+ * @returns 经过所有拦截器处理后的数据
90
+ */
91
+ async intercept(t) {
92
+ let e = t;
93
+ for (let s of this.interceptors)
94
+ s && (e = await s.intercept(e));
95
+ return e;
96
+ }
97
+ }
98
+ class E {
99
+ constructor() {
100
+ this.request = new h(), this.response = new h(), this.error = new h();
101
+ }
102
+ }
103
+ const w = {
104
+ baseURL: ""
105
+ };
106
+ class P {
107
+ /**
108
+ * 创建Fetcher实例
109
+ *
110
+ * @param options - Fetcher配置选项
111
+ */
112
+ constructor(t = w) {
113
+ this.interceptors = new E(), this.urlBuilder = new m(t.baseURL), this.headers = t.headers, this.timeout = t.timeout;
114
+ }
115
+ /**
116
+ * 发起HTTP请求
117
+ *
118
+ * @param url - 请求URL路径
119
+ * @param request - 请求选项,包括路径参数、查询参数等
120
+ * @returns Promise<Response> HTTP响应
121
+ */
122
+ async fetch(t, e = {}) {
123
+ const s = {
124
+ ...this.headers || {},
125
+ ...e.headers || {}
126
+ };
127
+ let n = {
128
+ ...e,
129
+ headers: Object.keys(s).length > 0 ? s : void 0
130
+ };
131
+ const o = this.urlBuilder.build(
132
+ t,
133
+ e.pathParams,
134
+ e.queryParams
135
+ );
136
+ n = await this.interceptors.request.intercept(n);
137
+ try {
138
+ let i = await this.timeoutFetch(o, n);
139
+ return i = await this.interceptors.response.intercept(i), i;
140
+ } catch (i) {
141
+ throw await this.interceptors.error.intercept(i);
142
+ }
143
+ }
144
+ /**
145
+ * 带超时控制的HTTP请求方法
146
+ *
147
+ * 该方法使用Promise.race来实现超时控制,同时发起fetch请求和超时Promise,
148
+ * 当任一Promise完成时,会返回其结果或抛出异常。
149
+ *
150
+ * @param url - 请求的URL地址
151
+ * @param request - 请求选项,包括method、headers、body等fetch API支持的选项
152
+ * @returns Promise<Response> HTTP响应Promise
153
+ * @throws FetchTimeoutError 当请求超时时抛出
154
+ */
155
+ async timeoutFetch(t, e) {
156
+ const s = d(e.timeout, this.timeout);
157
+ if (!s)
158
+ return fetch(t, e);
159
+ const n = new AbortController(), o = {
160
+ ...e,
161
+ signal: n.signal
162
+ };
163
+ let i = null;
164
+ const u = new Promise((y, l) => {
165
+ i = setTimeout(() => {
166
+ n.abort(), l(new a(t, e, s));
167
+ }, s);
168
+ });
169
+ try {
170
+ return await Promise.race([fetch(t, o), u]);
171
+ } finally {
172
+ i && clearTimeout(i);
173
+ }
174
+ }
175
+ /**
176
+ * 发起GET请求
177
+ *
178
+ * @param url - 请求URL路径
179
+ * @param request - 请求选项,包括路径参数、查询参数等
180
+ * @returns Promise<Response> HTTP响应
181
+ */
182
+ async get(t, e = {}) {
183
+ return this.fetch(t, {
184
+ ...e,
185
+ method: c.GET
186
+ });
187
+ }
188
+ /**
189
+ * 发起POST请求
190
+ *
191
+ * @param url - 请求URL路径
192
+ * @param request - 请求选项,包括路径参数、查询参数、请求体等
193
+ * @returns Promise<Response> HTTP响应
194
+ */
195
+ async post(t, e = {}) {
196
+ return this.fetch(t, {
197
+ ...e,
198
+ method: c.POST
199
+ });
200
+ }
201
+ /**
202
+ * 发起PUT请求
203
+ *
204
+ * @param url - 请求URL路径
205
+ * @param request - 请求选项,包括路径参数、查询参数、请求体等
206
+ * @returns Promise<Response> HTTP响应
207
+ */
208
+ async put(t, e = {}) {
209
+ return this.fetch(t, {
210
+ ...e,
211
+ method: c.PUT
212
+ });
213
+ }
214
+ /**
215
+ * 发起DELETE请求
216
+ *
217
+ * @param url - 请求URL路径
218
+ * @param request - 请求选项,包括路径参数、查询参数等
219
+ * @returns Promise<Response> HTTP响应
220
+ */
221
+ async delete(t, e = {}) {
222
+ return this.fetch(t, {
223
+ ...e,
224
+ method: c.DELETE
225
+ });
226
+ }
227
+ /**
228
+ * 发起PATCH请求
229
+ *
230
+ * @param url - 请求URL路径
231
+ * @param request - 请求选项,包括路径参数、查询参数、请求体等
232
+ * @returns Promise<Response> HTTP响应
233
+ */
234
+ async patch(t, e = {}) {
235
+ return this.fetch(t, {
236
+ ...e,
237
+ method: c.PATCH
238
+ });
239
+ }
240
+ /**
241
+ * 发起HEAD请求
242
+ *
243
+ * @param url - 请求URL路径
244
+ * @param request - 请求选项,包括路径参数、查询参数等
245
+ * @returns Promise<Response> HTTP响应
246
+ */
247
+ async head(t, e = {}) {
248
+ return this.fetch(t, {
249
+ ...e,
250
+ method: c.HEAD
251
+ });
252
+ }
253
+ /**
254
+ * 发起OPTIONS请求
255
+ *
256
+ * @param url - 请求URL路径
257
+ * @param request - 请求选项,包括路径参数、查询参数等
258
+ * @returns Promise<Response> HTTP响应
259
+ */
260
+ async options(t, e = {}) {
261
+ return this.fetch(t, {
262
+ ...e,
263
+ method: c.OPTIONS
264
+ });
265
+ }
266
+ }
267
+ export {
268
+ a as FetchTimeoutError,
269
+ P as Fetcher,
270
+ c as HttpMethod,
271
+ T as RequestField,
272
+ m as UrlBuilder,
273
+ p as combineURLs,
274
+ f as isAbsoluteURL,
275
+ d as resolveTimeout
276
+ };
@@ -0,0 +1 @@
1
+ (function(i,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(i=typeof globalThis<"u"?globalThis:i||self,u(i.FetcherCore={}))})(this,(function(i){"use strict";function u(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function f(r,e){return u(e)?e:e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}class d{constructor(e){this.baseURL=e}build(e,t,s){let n=f(this.baseURL,e),h=this.interpolateUrl(n,t);if(s){const o=new URLSearchParams(s).toString();o&&(h+="?"+o)}return h}interpolateUrl(e,t){return t?e.replace(/{([^}]+)}/g,(s,n)=>{const h=t[n];if(h===void 0)throw new Error(`Missing required path parameter: ${n}`);return String(h)}):e}}function m(r,e){return typeof r<"u"?r:e}class a extends Error{constructor(e,t,s){const n=`Request timeout of ${s}ms exceeded for ${t?.method||"GET"} ${e}`;super(n),this.name="FetchTimeoutError",this.url=e,this.request=t,Object.setPrototypeOf(this,a.prototype)}}var c=(r=>(r.GET="GET",r.POST="POST",r.PUT="PUT",r.DELETE="DELETE",r.PATCH="PATCH",r.HEAD="HEAD",r.OPTIONS="OPTIONS",r))(c||{}),p=(r=>(r.METHOD="method",r.BODY="body",r))(p||{});class l{constructor(){this.interceptors=[]}use(e){const t=this.interceptors.length;return this.interceptors.push(e),t}eject(e){this.interceptors[e]&&(this.interceptors[e]=null)}clear(){this.interceptors=[]}async intercept(e){let t=e;for(let s of this.interceptors)s&&(t=await s.intercept(t));return t}}class E{constructor(){this.request=new l,this.response=new l,this.error=new l}}const y={baseURL:""};class b{constructor(e=y){this.interceptors=new E,this.urlBuilder=new d(e.baseURL),this.headers=e.headers,this.timeout=e.timeout}async fetch(e,t={}){const s={...this.headers||{},...t.headers||{}};let n={...t,headers:Object.keys(s).length>0?s:void 0};const h=this.urlBuilder.build(e,t.pathParams,t.queryParams);n=await this.interceptors.request.intercept(n);try{let o=await this.timeoutFetch(h,n);return o=await this.interceptors.response.intercept(o),o}catch(o){throw await this.interceptors.error.intercept(o)}}async timeoutFetch(e,t){const s=m(t.timeout,this.timeout);if(!s)return fetch(e,t);const n=new AbortController,h={...t,signal:n.signal};let o=null;const T=new Promise((P,w)=>{o=setTimeout(()=>{n.abort(),w(new a(e,t,s))},s)});try{return await Promise.race([fetch(e,h),T])}finally{o&&clearTimeout(o)}}async get(e,t={}){return this.fetch(e,{...t,method:c.GET})}async post(e,t={}){return this.fetch(e,{...t,method:c.POST})}async put(e,t={}){return this.fetch(e,{...t,method:c.PUT})}async delete(e,t={}){return this.fetch(e,{...t,method:c.DELETE})}async patch(e,t={}){return this.fetch(e,{...t,method:c.PATCH})}async head(e,t={}){return this.fetch(e,{...t,method:c.HEAD})}async options(e,t={}){return this.fetch(e,{...t,method:c.OPTIONS})}}i.FetchTimeoutError=a,i.Fetcher=b,i.HttpMethod=c,i.RequestField=p,i.UrlBuilder=d,i.combineURLs=f,i.isAbsoluteURL=u,i.resolveTimeout=m,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,87 @@
1
+ import { FetcherRequest } from './fetcher';
2
+ /**
3
+ * 拦截器接口,定义了拦截器的基本结构
4
+ * @template T - 拦截器处理的数据类型
5
+ */
6
+ export interface Interceptor<T> {
7
+ /**
8
+ * 拦截并处理数据
9
+ * @param data - 需要处理的数据
10
+ * @returns 处理后的数据,可以是同步或异步返回
11
+ */
12
+ intercept(data: T): T | Promise<T>;
13
+ }
14
+ /**
15
+ * 请求拦截器接口,专门用于处理请求数据
16
+ */
17
+ export interface RequestInterceptor extends Interceptor<FetcherRequest> {
18
+ }
19
+ /**
20
+ * 响应拦截器接口,专门用于处理响应数据
21
+ */
22
+ export interface ResponseInterceptor extends Interceptor<Response> {
23
+ }
24
+ /**
25
+ * 错误拦截器接口,专门用于处理错误数据
26
+ */
27
+ export interface ErrorInterceptor extends Interceptor<any> {
28
+ }
29
+ /**
30
+ * 拦截器管理器类,用于管理同一类型的多个拦截器
31
+ * @template R - 拦截器处理的数据类型
32
+ * @template T - 拦截器类型
33
+ */
34
+ export declare class InterceptorManager<R, T extends Interceptor<R>> implements Interceptor<R> {
35
+ private interceptors;
36
+ /**
37
+ * 添加拦截器到管理器中
38
+ * @param interceptor - 要添加的拦截器
39
+ * @returns 拦截器在管理器中的索引位置
40
+ */
41
+ use(interceptor: T): number;
42
+ /**
43
+ * 根据索引移除拦截器
44
+ * @param index - 要移除的拦截器索引
45
+ */
46
+ eject(index: number): void;
47
+ /**
48
+ * 清空所有拦截器
49
+ */
50
+ clear(): void;
51
+ /**
52
+ * 依次执行所有拦截器对数据的处理
53
+ * @param data - 需要处理的数据
54
+ * @returns 经过所有拦截器处理后的数据
55
+ */
56
+ intercept(data: R): Promise<R>;
57
+ }
58
+ /**
59
+ * 请求拦截器管理器类型定义
60
+ */
61
+ export type RequestInterceptorManager = InterceptorManager<FetcherRequest, RequestInterceptor>;
62
+ /**
63
+ * 响应拦截器管理器类型定义
64
+ */
65
+ export type ResponseInterceptorManager = InterceptorManager<Response, ResponseInterceptor>;
66
+ /**
67
+ * 错误拦截器管理器类型定义
68
+ */
69
+ export type ErrorInterceptorManager = InterceptorManager<any, ErrorInterceptor>;
70
+ /**
71
+ * Fetcher拦截器集合类,包含请求、响应和错误拦截器管理器
72
+ */
73
+ export declare class FetcherInterceptors {
74
+ /**
75
+ * 请求拦截器管理器
76
+ */
77
+ request: RequestInterceptorManager;
78
+ /**
79
+ * 响应拦截器管理器
80
+ */
81
+ response: ResponseInterceptorManager;
82
+ /**
83
+ * 错误拦截器管理器
84
+ */
85
+ error: ErrorInterceptorManager;
86
+ }
87
+ //# sourceMappingURL=interceptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C;;;GAGG;AACH,MAAM,WAAW,WAAW,CAAC,CAAC;IAC5B;;;;OAIG;IACH,SAAS,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACpC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,WAAW,CAAC,cAAc,CAAC;CAAG;AAE1E;;GAEG;AACH,MAAM,WAAW,mBAAoB,SAAQ,WAAW,CAAC,QAAQ,CAAC;CAAG;AAErE;;GAEG;AACH,MAAM,WAAW,gBAAiB,SAAQ,WAAW,CAAC,GAAG,CAAC;CAAG;AAE7D;;;;GAIG;AACH,qBAAa,kBAAkB,CAAC,CAAC,EAAE,CAAC,SAAS,WAAW,CAAC,CAAC,CAAC,CACzD,YAAW,WAAW,CAAC,CAAC,CAAC;IAEzB,OAAO,CAAC,YAAY,CAAuB;IAE3C;;;;OAIG;IACH,GAAG,CAAC,WAAW,EAAE,CAAC,GAAG,MAAM;IAM3B;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAM1B;;OAEG;IACH,KAAK,IAAI,IAAI;IAIb;;;;OAIG;IACG,SAAS,CAAC,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAUrC;AAED;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG,kBAAkB,CACxD,cAAc,EACd,kBAAkB,CACnB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,kBAAkB,CACzD,QAAQ,EACR,mBAAmB,CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,kBAAkB,CAAC,GAAG,EAAE,gBAAgB,CAAC,CAAC;AAEhF;;GAEG;AACH,qBAAa,mBAAmB;IAC9B;;OAEG;IACH,OAAO,EAAE,yBAAyB,CAG9B;IAEJ;;OAEG;IACH,QAAQ,EAAE,0BAA0B,CAGhC;IAEJ;;OAEG;IACH,KAAK,EAAE,uBAAuB,CAG1B;CACL"}
@@ -0,0 +1,29 @@
1
+ import { FetcherRequest } from './fetcher';
2
+ /**
3
+ * 定义具有超时能力的接口
4
+ */
5
+ export interface TimeoutCapable {
6
+ /**
7
+ * 请求超时
8
+ * 当值为0时,表示不设置超时,默认值为 undefined
9
+ */
10
+ timeout?: number;
11
+ }
12
+ /**
13
+ * 解析请求超时设置,优先使用请求级别的超时设置
14
+ *
15
+ * @param requestTimeout - 请求级别的超时设置
16
+ * @param optionsTimeout - 配置级别的超时设置
17
+ * @returns 解析后的超时设置
18
+ */
19
+ export declare function resolveTimeout(requestTimeout?: number, optionsTimeout?: number): number | undefined;
20
+ /**
21
+ * FetchTimeoutError 异常类
22
+ * 当HTTP请求超时时抛出此异常
23
+ */
24
+ export declare class FetchTimeoutError extends Error {
25
+ url: string;
26
+ request: FetcherRequest;
27
+ constructor(url: string, request: FetcherRequest, timeout: number);
28
+ }
29
+ //# sourceMappingURL=timeout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,cAAc,CAAC,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,cAAc,CAAC;gBAEZ,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM;CAUlE"}
@@ -0,0 +1,30 @@
1
+ export interface BaseURLCapable {
2
+ /**
3
+ * 请求的 baseURL
4
+ * 当值为空时,表示不设置 baseURL,默认值为 undefined
5
+ */
6
+ baseURL: string;
7
+ }
8
+ export interface HeadersCapable {
9
+ /**
10
+ * 请求头
11
+ */
12
+ headers?: Record<string, string>;
13
+ }
14
+ /**
15
+ * HTTP方法枚举常量
16
+ */
17
+ export declare enum HttpMethod {
18
+ GET = "GET",
19
+ POST = "POST",
20
+ PUT = "PUT",
21
+ DELETE = "DELETE",
22
+ PATCH = "PATCH",
23
+ HEAD = "HEAD",
24
+ OPTIONS = "OPTIONS"
25
+ }
26
+ export declare enum RequestField {
27
+ METHOD = "method",
28
+ BODY = "body"
29
+ }
30
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,OAAO,YAAY;CACpB;AAED,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;CACd"}
@@ -0,0 +1,38 @@
1
+ import { BaseURLCapable } from './types';
2
+ /**
3
+ * URL构建器类,用于构建带有路径参数和查询参数的完整URL
4
+ *
5
+ * @example
6
+ * const urlBuilder = new UrlBuilder('https://api.example.com');
7
+ * const url = urlBuilder.build('/users/{id}', { id: 123 }, { filter: 'active' });
8
+ * // 结果: https://api.example.com/users/123?filter=active
9
+ */
10
+ export declare class UrlBuilder implements BaseURLCapable {
11
+ baseURL: string;
12
+ /**
13
+ * 创建UrlBuilder实例
14
+ *
15
+ * @param baseURL - 基础URL,所有构建的URL都将基于此URL
16
+ */
17
+ constructor(baseURL: string);
18
+ /**
19
+ * 构建完整的URL,包括路径参数替换和查询参数添加
20
+ *
21
+ * @param url - 需要构建的URL路径
22
+ * @param pathParams - 路径参数对象,用于替换URL中的占位符(如{id})
23
+ * @param queryParams - 查询参数对象,将被添加到URL查询字符串中
24
+ * @returns 完整的URL字符串
25
+ * @throws 当路径参数中缺少必需的占位符时抛出错误
26
+ */
27
+ build(url: string, pathParams?: Record<string, any>, queryParams?: Record<string, any>): string;
28
+ /**
29
+ * 替换url中的占位符参数
30
+ *
31
+ * @param url - 包含占位符的路径字符串,如 "http://localhost/users/{id}/posts/{postId}"
32
+ * @param pathParams - 路径参数对象,用于替换路径中的占位符
33
+ * @returns 替换占位符后的路径字符串
34
+ * @throws 当路径参数中缺少必需的占位符时抛出错误
35
+ */
36
+ interpolateUrl(url: string, pathParams?: Record<string, any>): string;
37
+ }
38
+ //# sourceMappingURL=urlBuilder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"urlBuilder.d.ts","sourceRoot":"","sources":["../src/urlBuilder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC;;;;;;;GAOG;AACH,qBAAa,UAAW,YAAW,cAAc;IAC/C,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;OAIG;gBACS,OAAO,EAAE,MAAM;IAI3B;;;;;;;;OAQG;IACH,KAAK,CACH,GAAG,EAAE,MAAM,EACX,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAChC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAChC,MAAM;IAYT;;;;;;;OAOG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;CAWtE"}
package/dist/urls.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare function isAbsoluteURL(url: string): boolean;
2
+ export declare function combineURLs(baseURL: string, relativeURL: string): string;
3
+ //# sourceMappingURL=urls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"urls.d.ts","sourceRoot":"","sources":["../src/urls.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,WAExC;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,UAQ/D"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@ahoo-wang/fetcher",
3
+ "version": "0.0.1",
4
+ "description": "Core library providing basic HTTP client functionality for Fetcher",
5
+ "keywords": [
6
+ "fetch",
7
+ "http",
8
+ "client",
9
+ "axios"
10
+ ],
11
+ "author": "Ahoo-Wang",
12
+ "license": "Apache-2.0",
13
+ "homepage": "https://github.com/Ahoo-Wang/fetcher/tree/master/packages/core",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/Ahoo-Wang/fetcher.git",
17
+ "directory": "packages/core"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/Ahoo-Wang/fetcher/issues"
21
+ },
22
+ "main": "./dist/index.umd.js",
23
+ "module": "./dist/index.es.js",
24
+ "types": "./dist/index.d.ts",
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "devDependencies": {
29
+ "@vitest/coverage-v8": "^3.2.4",
30
+ "eslint": "^9.33.0",
31
+ "prettier": "^3.6.2",
32
+ "typescript": "^5.9.2",
33
+ "unplugin-dts": "1.0.0-beta.6",
34
+ "vite": "^7.1.3",
35
+ "vitest": "^3.2.4"
36
+ },
37
+ "scripts": {
38
+ "build": "vite build",
39
+ "test": "vitest run --coverage",
40
+ "lint": "tsc --noEmit",
41
+ "clean": "rm -rf dist"
42
+ }
43
+ }