hook-fetch 0.0.2-beta → 0.0.2

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/README.en.md CHANGED
@@ -1,17 +1,283 @@
1
-
2
1
  # Hook-Fetch 🚀
3
2
 
4
3
  **[中文文档](https://github.com/JsonLee12138/hook-fetch/blob/main/README.md)**
5
4
 
6
- Both usage documentation and development documentation are still under development.
7
- Please refer to [unit tests](https://github.com/JsonLee12138/hook-fetch/blob/main/test/index.test.ts) for usage instructions.
5
+ ## Introduction
6
+
7
+ Hook-Fetch is a powerful request library based on the native fetch API, offering a simpler syntax, richer features, and a more flexible plugin system. It supports request retries, streaming data processing, request cancellation, and more. With its Promise-based chaining style, API requests become simpler and more controllable.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ # Using npm
13
+ npm install hook-fetch
14
+
15
+ # Using yarn
16
+ yarn add hook-fetch
17
+
18
+ # Using pnpm
19
+ pnpm add hook-fetch
20
+ ```
21
+
22
+ ## Basic Usage
23
+
24
+ ### Making a Simple Request
25
+
26
+ ```typescript
27
+ import hookFetch from 'hook-fetch';
28
+
29
+ // Make a GET request
30
+ const response = await hookFetch('https://example.com/api/data');
31
+ console.log(response); // Response data is automatically parsed as JSON
32
+
33
+ // Using other HTTP methods
34
+ const postResponse = await hookFetch('https://example.com/api/data', {
35
+ method: 'POST',
36
+ data: { name: 'hook-fetch' }
37
+ });
38
+ ```
39
+
40
+ ### Creating an Instance
41
+
42
+ ```typescript
43
+ // Create an instance with a base URL
44
+ const api = hookFetch.create({
45
+ baseURL: 'https://example.com',
46
+ headers: {
47
+ 'Content-Type': 'application/json',
48
+ },
49
+ timeout: 5000, // Timeout in milliseconds
50
+ });
51
+
52
+ // Use the instance to make requests
53
+ const userData = await api.get('/users/1');
54
+ ```
55
+
56
+ ### HTTP Request Methods
57
+
58
+ ```typescript
59
+ // GET request
60
+ const data = await api.get('/users', { page: 1, limit: 10 });
61
+
62
+ // POST request
63
+ const newUser = await api.post('/users', { name: 'John', age: 30 });
64
+
65
+ // PUT request
66
+ const updatedUser = await api.put('/users/1', { name: 'John Doe' });
67
+
68
+ // PATCH request
69
+ const patchedUser = await api.patch('/users/1', { age: 31 });
70
+
71
+ // DELETE request
72
+ const deleted = await api.delete('/users/1');
73
+
74
+ // HEAD request
75
+ const headers = await api.head('/users/1');
76
+
77
+ // OPTIONS request
78
+ const options = await api.options('/users');
79
+ ```
80
+
81
+ ## Advanced Features
82
+
83
+ ### Response Handling
84
+
85
+ Hook-Fetch supports various response data handling methods:
86
+
87
+ ```typescript
88
+ const req = hookFetch('https://example.com/api/data');
89
+
90
+ // JSON parsing (default)
91
+ const jsonData = await req;
92
+
93
+ // Text parsing
94
+ const textData = await req.text();
95
+
96
+ // Blob handling
97
+ const blobData = await req.blob();
98
+
99
+ // ArrayBuffer handling
100
+ const arrayBufferData = await req.arrayBuffer();
101
+
102
+ // FormData handling
103
+ const formDataResult = await req.formData();
104
+
105
+ // Byte stream handling
106
+ const bytesData = await req.bytes();
107
+ ```
108
+
109
+ ### Cancelling Requests
110
+
111
+ ```typescript
112
+ const req = api.get('/long-running-process');
113
+
114
+ // Cancel the request later
115
+ setTimeout(() => {
116
+ req.abort();
117
+ }, 1000);
118
+ ```
119
+
120
+ ### Request Retry
121
+
122
+ ```typescript
123
+ // Make a request
124
+ const req = api.get('/users/1');
125
+
126
+ // Cancel the request
127
+ req.abort();
8
128
 
9
- Planned Development
129
+ // Retry the request
130
+ const newReq = req.retry();
131
+ const result = await newReq;
132
+ ```
10
133
 
11
- - Support for static methods like get, post, etc.
12
- - Support for umd
13
- - Support for request retry functionality
134
+ ### Streaming Data Processing
135
+
136
+ ```typescript
137
+ const req = hookFetch('https://sse.dev/test');
138
+
139
+ // Process streaming data
140
+ for await (const chunk of req.stream()) {
141
+ console.log(chunk.result);
142
+ }
143
+ ```
144
+
145
+ ### Plugin System
146
+
147
+ Hook-Fetch offers a robust plugin system allowing intervention at various stages of the request lifecycle:
148
+
149
+ ```typescript
150
+ // Custom plugin example: SSE text decoding plugin
151
+ // This is just an example. You can use the provided plugin `sseTextDecoderPlugin`
152
+ const ssePlugin = () => {
153
+ const decoder = new TextDecoder('utf-8');
154
+ return {
155
+ name: 'sse',
156
+ async transformStreamChunk(chunk) {
157
+ if (!chunk.error) {
158
+ chunk.result = decoder.decode(chunk.result, { stream: true });
159
+ }
160
+ return chunk;
161
+ }
162
+ }
163
+ };
164
+
165
+ // Register the plugin
166
+ api.use(ssePlugin());
167
+
168
+ // Use the request with the plugin
169
+ const req = api.get('/sse-endpoint');
170
+ for await (const chunk of req.stream<string>()) {
171
+ console.log(chunk.result); // Processed into text by the plugin
172
+ }
173
+ ```
174
+
175
+ Plugin hooks:
176
+ - `beforeRequest`: Handle configuration before sending the request
177
+ - `afterResponse`: Process data after receiving the response
178
+ - `transformStreamChunk`: Handle streaming data chunks
179
+ - `onError`: Handle request errors
180
+ - `onFinally`: Callback after request completion
181
+
182
+ ## Generic Support
183
+
184
+ Hook-Fetch provides comprehensive TypeScript support, allowing you to define explicit types for requests and responses:
185
+
186
+ ```typescript
187
+ // Define response data type
188
+ interface User {
189
+ id: number;
190
+ name: string;
191
+ email: string;
192
+ }
193
+
194
+ // Use the type in a request
195
+ const user = await api.get<User>('/users/1');
196
+ console.log(user.name); // TypeScript provides complete type hints
197
+ ```
198
+
199
+ ## Complete API
200
+
201
+ ### Request Configuration Options
202
+
203
+ ```typescript
204
+ interface RequestOptions {
205
+ // Base URL for requests
206
+ baseURL: string;
207
+
208
+ // Request timeout (milliseconds)
209
+ timeout: number;
210
+
211
+ // Request headers
212
+ headers: HeadersInit;
213
+
214
+ // List of plugins
215
+ plugins: Array<HookFetchPlugin>;
216
+
217
+ // Whether to include credentials (cookies, etc.)
218
+ withCredentials: boolean;
219
+
220
+ // URL parameters
221
+ params: any;
222
+
223
+ // Request body data
224
+ data: any;
225
+
226
+ // Controller (for cancelling requests)
227
+ controller: AbortController;
228
+
229
+ // Extra data (can be passed to plugins)
230
+ extra: any;
231
+
232
+ // Array parameter serialization format
233
+ qsArrayFormat: 'indices' | 'brackets' | 'repeat' | 'comma';
234
+
235
+ // Request method
236
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
237
+ }
238
+ ```
239
+
240
+ ### Plugin Type
241
+
242
+ ```typescript
243
+ interface HookFetchPlugin<T = unknown, E = unknown, P = unknown, D = unknown> {
244
+ // Plugin name
245
+ name: string;
246
+
247
+ // Priority (lower numbers have higher priority)
248
+ priority?: number;
249
+
250
+ // Pre-request processing
251
+ beforeRequest?: (config: RequestConfig) => Promise<RequestConfig>;
252
+
253
+ // Post-response processing
254
+ afterResponse?: (context: FetchPluginContext) => Promise<FetchPluginContext>;
255
+
256
+ // Stream data chunk transformation
257
+ transformStreamChunk?: (chunk: StreamContext) => Promise<StreamContext>;
258
+
259
+ // Error handling
260
+ onError?: (error: Error) => Promise<Error | void | ResponseError>;
261
+
262
+ // Request completion processing
263
+ onFinally?: (context: FetchPluginContext) => Promise<void>;
264
+ }
265
+ ```
266
+
267
+ ## Notes
268
+
269
+ 1. Hook-Fetch automatically parses JSON responses by default.
270
+ 2. All request methods return Promise objects.
271
+ 3. You can retry aborted requests using the `.retry()` method.
272
+ 4. Plugins execute in order of priority.
273
+
274
+ ## Upcoming Features
275
+ - `umd` support
14
276
  - More plugin support
277
+
278
+ ## 📝 Contribution Guide
279
+ Feel free to submit `issues` or `pull requests` to help improve `Hook-Fetch`.
280
+
15
281
  ## 📄 License
16
282
 
17
283
  MIT
package/README.md CHANGED
@@ -2,14 +2,282 @@
2
2
 
3
3
  **[English document](https://github.com/JsonLee12138/hook-fetch/blob/main/README.en.md)**
4
4
 
5
- 当前使用文档和开发文档都还在开发中
6
- 使用方法请先参阅[单元测试](https://github.com/JsonLee12138/hook-fetch/blob/main/test/index.test.ts)
5
+ ## 介绍
7
6
 
8
- 预计开发内容
9
- - 支持`get`、`post`等等静态方法。
7
+ Hook-Fetch 是一个强大的基于原生 fetch API 的请求库,提供了更简洁的语法、更丰富的功能和更灵活的插件系统。它支持请求重试、流式数据处理、中断请求等特性,并且采用Promise链式调用风格,使API请求变得更加简单和可控。
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ # 使用 npm
13
+ npm install hook-fetch
14
+
15
+ # 使用 yarn
16
+ yarn add hook-fetch
17
+
18
+ # 使用 pnpm
19
+ pnpm add hook-fetch
20
+ ```
21
+
22
+ ## 基础使用
23
+
24
+ ### 发起简单请求
25
+
26
+ ```typescript
27
+ import hookFetch from 'hook-fetch';
28
+
29
+ // 发起 GET 请求
30
+ const response = await hookFetch('https://example.com/api/data');
31
+ console.log(response); // 响应数据已自动解析为JSON
32
+
33
+ // 使用其他HTTP方法
34
+ const postResponse = await hookFetch('https://example.com/api/data', {
35
+ method: 'POST',
36
+ data: { name: 'hook-fetch' }
37
+ });
38
+ ```
39
+
40
+ ### 创建实例
41
+
42
+ ```typescript
43
+ // 创建一个配置好基础URL的实例
44
+ const api = hookFetch.create({
45
+ baseURL: 'https://example.com',
46
+ headers: {
47
+ 'Content-Type': 'application/json',
48
+ },
49
+ timeout: 5000, // 超时时间 (毫秒)
50
+ });
51
+
52
+ // 使用实例发起请求
53
+ const userData = await api.get('/users/1');
54
+ ```
55
+
56
+ ### HTTP请求方法
57
+
58
+ ```typescript
59
+ // GET 请求
60
+ const data = await api.get('/users', { page: 1, limit: 10 });
61
+
62
+ // POST 请求
63
+ const newUser = await api.post('/users', { name: 'John', age: 30 });
64
+
65
+ // PUT 请求
66
+ const updatedUser = await api.put('/users/1', { name: 'John Doe' });
67
+
68
+ // PATCH 请求
69
+ const patchedUser = await api.patch('/users/1', { age: 31 });
70
+
71
+ // DELETE 请求
72
+ const deleted = await api.delete('/users/1');
73
+
74
+ // HEAD 请求
75
+ const headers = await api.head('/users/1');
76
+
77
+ // OPTIONS 请求
78
+ const options = await api.options('/users');
79
+ ```
80
+
81
+ ## 高级功能
82
+
83
+ ### 响应处理
84
+
85
+ Hook-Fetch 支持多种响应数据处理方式:
86
+
87
+ ```typescript
88
+ const req = hookFetch('https://example.com/api/data');
89
+
90
+ // JSON 解析 (默认)
91
+ const jsonData = await req;
92
+
93
+ // 文本解析
94
+ const textData = await req.text();
95
+
96
+ // Blob 处理
97
+ const blobData = await req.blob();
98
+
99
+ // ArrayBuffer 处理
100
+ const arrayBufferData = await req.arrayBuffer();
101
+
102
+ // FormData 处理
103
+ const formDataResult = await req.formData();
104
+
105
+ // 字节流处理
106
+ const bytesData = await req.bytes();
107
+ ```
108
+
109
+ ### 中断请求
110
+
111
+ ```typescript
112
+ const req = api.get('/long-running-process');
113
+
114
+ // 稍后中断请求
115
+ setTimeout(() => {
116
+ req.abort();
117
+ }, 1000);
118
+ ```
119
+
120
+ ### 请求重试
121
+
122
+ ```typescript
123
+ // 发起请求
124
+ const req = api.get('/users/1');
125
+
126
+ // 中断请求
127
+ req.abort();
128
+
129
+ // 重试请求
130
+ const newReq = req.retry();
131
+ const result = await newReq;
132
+ ```
133
+
134
+ ### 流式数据处理
135
+
136
+ ```typescript
137
+ const req = hookFetch('https://sse.dev/test');
138
+
139
+ // 处理流式数据
140
+ for await (const chunk of req.stream()) {
141
+ console.log(chunk.result);
142
+ }
143
+ ```
144
+
145
+ ### 插件系统
146
+
147
+ Hook-Fetch 提供了强大的插件系统,可以在请求生命周期的各个阶段进行干预:
148
+
149
+ ```typescript
150
+ // 自定义插件示例:SSE文本解码插件
151
+ // 当前只是示例, 您可以直接饮用我提供的插件`sseTextDecoderPlugin`
152
+ const ssePlugin = () => {
153
+ const decoder = new TextDecoder('utf-8');
154
+ return {
155
+ name: 'sse',
156
+ async transformStreamChunk(chunk) {
157
+ if (!chunk.error) {
158
+ chunk.result = decoder.decode(chunk.result, { stream: true });
159
+ }
160
+ return chunk;
161
+ }
162
+ }
163
+ };
164
+
165
+ // 注册插件
166
+ api.use(ssePlugin());
167
+
168
+ // 使用带插件的请求
169
+ const req = api.get('/sse-endpoint');
170
+ for await (const chunk of req.stream<string>()) {
171
+ console.log(chunk.result); // 已被插件处理成文本
172
+ }
173
+ ```
174
+
175
+ 插件钩子函数:
176
+ - `beforeRequest`: 请求发送前处理配置
177
+ - `afterResponse`: 响应接收后处理数据
178
+ - `transformStreamChunk`: 处理流式数据块
179
+ - `onError`: 处理请求错误
180
+ - `onFinally`: 请求完成后的回调
181
+
182
+ ## 泛型支持
183
+
184
+ Hook-Fetch 提供了完善的TypeScript类型支持,可以为请求和响应定义明确的类型:
185
+
186
+ ```typescript
187
+ // 定义响应数据类型
188
+ interface User {
189
+ id: number;
190
+ name: string;
191
+ email: string;
192
+ }
193
+
194
+ // 在请求中使用类型
195
+ const user = await api.get<User>('/users/1');
196
+ console.log(user.name); // TypeScript提供完整类型提示
197
+ ```
198
+
199
+ ## 完整API
200
+
201
+ ### 请求配置选项
202
+
203
+ ```typescript
204
+ interface RequestOptions {
205
+ // 请求基础URL
206
+ baseURL: string;
207
+
208
+ // 请求超时时间 (毫秒)
209
+ timeout: number;
210
+
211
+ // 请求头
212
+ headers: HeadersInit;
213
+
214
+ // 插件列表
215
+ plugins: Array<HookFetchPlugin>;
216
+
217
+ // 是否携带凭证 (cookies等)
218
+ withCredentials: boolean;
219
+
220
+ // URL参数
221
+ params: any;
222
+
223
+ // 请求体数据
224
+ data: any;
225
+
226
+ // 控制器 (用于中断请求)
227
+ controller: AbortController;
228
+
229
+ // 额外数据 (可传递给插件)
230
+ extra: any;
231
+
232
+ // 数组参数序列化格式
233
+ qsArrayFormat: 'indices' | 'brackets' | 'repeat' | 'comma';
234
+
235
+ // 请求方法
236
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
237
+ }
238
+ ```
239
+
240
+ ### 插件类型
241
+
242
+ ```typescript
243
+ interface HookFetchPlugin<T = unknown, E = unknown, P = unknown, D = unknown> {
244
+ // 插件名称
245
+ name: string;
246
+
247
+ // 优先级 (数字越小优先级越高)
248
+ priority?: number;
249
+
250
+ // 请求前处理
251
+ beforeRequest?: (config: RequestConfig) => Promise<RequestConfig>;
252
+
253
+ // 响应后处理
254
+ afterResponse?: (context: FetchPluginContext) => Promise<FetchPluginContext>;
255
+
256
+ // 流数据块转换
257
+ transformStreamChunk?: (chunk: StreamContext) => Promise<StreamContext>;
258
+
259
+ // 错误处理
260
+ onError?: (error: Error) => Promise<Error | void | ResponseError>;
261
+
262
+ // 请求完成处理
263
+ onFinally?: (context: FetchPluginContext) => Promise<void>;
264
+ }
265
+ ```
266
+
267
+ ## 注意事项
268
+
269
+ 1. Hook-Fetch 默认会自动解析JSON响应
270
+ 2. 所有的请求方法都返回Promise对象
271
+ 3. 可以通过`.retry()`方法重试已中断的请求
272
+ 4. 插件按照优先级顺序执行
273
+
274
+ ## 预计开发内容
10
275
  - `umd` 支持
11
- - 支持重新发送请求功能。
12
276
  - 更多的插件支持
277
+
278
+ ## 📝 贡献指南
279
+ 欢迎提交`issue`或`pull request`,共同完善`Hook-Fetch`。
280
+
13
281
  ## 📄 许可证
14
282
 
15
283
  MIT