hook-fetch 2.1.4 → 2.1.6

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/CHANGELOG.md ADDED
@@ -0,0 +1,161 @@
1
+ # hook-fetch
2
+
3
+ ## 2.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - 修复错误异常问题
8
+
9
+ ## 2.1.5
10
+
11
+ ### Patch Changes
12
+
13
+ - 更新文档
14
+
15
+ ## 2.1.4
16
+
17
+ ### Patch Changes
18
+
19
+ - 修复beforeRequest中不能抛错的问题
20
+
21
+ ## 2.1.3
22
+
23
+ ### Patch Changes
24
+
25
+ - 修复stream方法的错误不会走plugin的错误生命周期的bug
26
+
27
+ ## 2.1.2
28
+
29
+ ### Patch Changes
30
+
31
+ - 修复抛出的HookFetchRequest类型不支持泛型的问题
32
+
33
+ ## 2.1.1
34
+
35
+ ### Patch Changes
36
+
37
+ - 8d4d6b6: 修复HookFetchRequest实例没有抛出的问题
38
+
39
+ ## 2.1.1-beta.0
40
+
41
+ ### Patch Changes
42
+
43
+ - 修复HookFetchRequest实例没有抛出的问题
44
+
45
+ ## 3.0.0-beta.0
46
+
47
+ ### Major Changes
48
+
49
+ - 4b15105: 修改changeset配置, 改用changeset进行发布
50
+
51
+ ## v2.1.0 💥
52
+
53
+ **发布日期**: 2025-08-08
54
+
55
+ #### 💔 破坏性变更
56
+
57
+ - 泛型签名调整:`HookFetch` 与 `hookFetch.create` 的泛型从
58
+ `<R extends AnyObject = AnyObject, K extends keyof R = 'data', E = AnyObject>`
59
+ 调整为
60
+ `<R extends AnyObject | null = null, K extends keyof R = never, E = AnyObject>`。
61
+ - 当 `R = null`(默认)时:`json<T>()` 的返回类型为 `T`,不做包裹映射(更贴近原生 fetch 的直觉)。
62
+ - 当你需要“包裹响应”并做键映射时:显式传入响应包裹类型和键名,例如 `hookFetch.create<ResponseVO, 'data'>(...)`,此时 `json<User>()` 的返回类型为 `ResponseVO` 且其中 `data` 为 `User`。
63
+
64
+ #### 🔧 迁移指南
65
+
66
+ - 旧代码:
67
+
68
+ ```ts
69
+ interface ResponseVO {
70
+ code: number;
71
+ message: string;
72
+ data: never;
73
+ }
74
+ const api = hookFetch.create<ResponseVO>({ baseURL: "..." });
75
+ const res = await api.get<User>("/user").json();
76
+ // res.data: User
77
+ ```
78
+
79
+ 新代码需显式指定键名:
80
+
81
+ ```ts
82
+ const api = hookFetch.create<ResponseVO, "data">({ baseURL: "..." });
83
+ const res = await api.get<User>("/user").json();
84
+ // res.data: User
85
+ ```
86
+
87
+ - 若无需包裹(直接拿到 `T`):
88
+ ```ts
89
+ const api = hookFetch.create(); // 等价于 <null, never>
90
+ const user = await api.get<User>("/user").json(); // user: User
91
+ ```
92
+
93
+ #### 🧰 其他
94
+
95
+ - 同步更新文档:README 与 API 参考已更新示例,明确 `R | null` 与 `K` 的用法。
96
+
97
+ ### v2.0.7 🛠️
98
+
99
+ **发布日期**: 2025-08-08
100
+
101
+ #### 🐛 修复
102
+
103
+ - 修复 `json`、`text`、`blob`、`arrayBuffer`、`formData`、`bytes` 方法的类型推断缺失问题(更完善的返回值类型提示)。
104
+
105
+ #### 🧱 基础设施
106
+
107
+ - 调整与修复发布 CI/CD 流程相关配置。
108
+
109
+ ### v2.0.6
110
+
111
+ **发布日期**: 2025-08-07
112
+
113
+ #### 🔧 变更
114
+
115
+ - 发布流程与版本稳定性相关的调整。
116
+
117
+ ### v2.0.3 🎉
118
+
119
+ **发布日期**: 2025-06-30
120
+
121
+ #### 💔 破坏性变更
122
+
123
+ - **移除默认JSON解析**: 不再自动解析JSON响应,需要显式调用 `.json()` 方法
124
+ - **更明确的响应处理**: 提供更明确的响应数据处理方式,避免隐式行为
125
+
126
+ #### 🔧 API 调整
127
+
128
+ - 所有请求方法现在需要显式调用响应处理方法(如 `.json()`, `.text()` 等)
129
+ - 提高了API的明确性和可预测性
130
+
131
+ #### 📚 文档更新
132
+
133
+ - 更新了所有示例代码,明确显示 `.json()` 调用
134
+ - 改进了响应处理的文档说明
135
+
136
+ ### v1.0.x
137
+
138
+ **发布日期**: 2025-04
139
+
140
+ #### 🎯 首次发布
141
+
142
+ - 基于原生 fetch API 的现代化 HTTP 请求库
143
+ - **自动JSON解析**: 默认自动解析JSON响应
144
+ - **完整插件系统**: 支持 `beforeRequest`, `afterResponse`, `beforeStream`, `transformStreamChunk`, `onError`, `onFinally` 生命周期钩子
145
+ - **Vue Hooks 支持**: 提供 `useHookFetch` Vue 组合式 API
146
+ - **React Hooks 支持**: 提供 `useHookFetch` React Hook
147
+ - **多种响应处理**: 支持 `json()`, `text()`, `blob()`, `arrayBuffer()`, `formData()`, `bytes()` 方法
148
+ - **请求重试机制**: 支持 `.retry()` 方法重试已中断的请求
149
+ - **流式数据处理**: 强大的流式响应处理能力
150
+ - **请求中断**: 支持 `.abort()` 方法中断请求
151
+ - **插件优先级**: 支持插件优先级设置
152
+ - **SSE 支持**: 提供 `sseTextDecoderPlugin` 插件
153
+ - **完整 TypeScript 支持**: 提供完善的类型定义和泛型支持
154
+ - **灵活配置**: 支持超时、baseURL、请求头、参数序列化等配置选项
155
+ - **VSCode 智能提示**: 提供专门的类型声明文件
156
+
157
+ ### 即将发布
158
+
159
+ - 更多内置插件
160
+ - 更丰富的插件生态
161
+ - 更多框架集成支持
package/README.en.md CHANGED
@@ -1,11 +1,18 @@
1
- # Hook-Fetch 🚀
1
+ <div align="center">
2
+ <a href="https://jsonlee12138.github.io/hook-fetch/"><img src="https://jsonlee12138.github.io/hook-fetch/img/logo.png" /></a><br>
3
+ </div>
4
+ <h1 align="center" style="margin-bottom: 0;">Hook-Fetch</h1>
5
+ <div align="center">
2
6
 
3
- **[中文文档](https://github.com/JsonLee12138/hook-fetch/blob/main/README.md)**
7
+ [![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=Release&logo=github&style=flat-square)](https://github.com/JsonLee12138/hook-fetch/actions/workflows/release.yml) [![install size](https://packagephobia.com/badge?p=hook-fetch)](https://packagephobia.com/result?p=hook-fetch) [![npm bundle size](https://img.shields.io/bundlephobia/minzip/hook-fetch?style=flat-square)](https://bundlephobia.com/package/hook-fetch@latest) [![npm downloads](https://img.shields.io/npm/dm/hook-fetch.svg?style=flat-square)](https://npm-stat.com/charts.html?package=hook-fetch) [![Discord](https://img.shields.io/badge/-Discord-5865F2?style=flat&logo=discord&logoColor=white)](https://discord.com/invite/666U6JTCQY)
4
8
 
5
- ## Introduction
9
+ **[中文文档](https://github.com/JsonLee12138/hook-fetch/blob/main/README.md)**
6
10
 
7
11
  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
12
 
13
+ </div>
14
+ <br />
15
+
9
16
  ## Installation
10
17
 
11
18
  ```bash
@@ -149,7 +156,7 @@ Hook-Fetch offers a robust plugin system allowing intervention at various stages
149
156
  ```typescript
150
157
  // Custom plugin example: SSE text decoding plugin
151
158
  // This is just an example. It's recommended to use the provided `sseTextDecoderPlugin` which has more comprehensive handling
152
- const ssePlugin = () => {
159
+ function ssePlugin() {
153
160
  const decoder = new TextDecoder('utf-8');
154
161
  return {
155
162
  name: 'sse',
@@ -159,8 +166,8 @@ const ssePlugin = () => {
159
166
  }
160
167
  return chunk;
161
168
  }
162
- }
163
- };
169
+ };
170
+ }
164
171
 
165
172
  // Register the plugin
166
173
  api.use(ssePlugin());
@@ -176,7 +183,7 @@ for await (const chunk of req.stream<string>()) {
176
183
 
177
184
  ```typescript
178
185
  // Complete plugin example showing the usage of each lifecycle hook
179
- const examplePlugin = () => {
186
+ function examplePlugin() {
180
187
  return {
181
188
  name: 'example',
182
189
  priority: 1, // Priority, lower numbers have higher priority
@@ -194,17 +201,18 @@ const examplePlugin = () => {
194
201
  // Can process response data. context.result is the result after being processed by methods like json()
195
202
  if (context.responseType === 'json') {
196
203
  // For example, determine if the request is truly successful based on the backend's business code
197
- if(context.result.code === 200){
204
+ if (context.result.code === 200) {
198
205
  // Business success, return context directly
199
- return context
200
- }else{
206
+ return context;
207
+ }
208
+ else {
201
209
  // Business failure, actively throw a ResponseError, which will be caught in the onError hook
202
210
  throw new ResponseError({
203
211
  message: context.result.message, // Use the error message from the backend
204
- status: context.result.code, // Use the business code as the status
205
- response: context.response, // Original Response object
212
+ status: context.result.code, // Use the business code as the status
213
+ response: context.response, // Original Response object
206
214
  config: context.config,
207
- name: 'BusinessError' // Custom error name
215
+ name: 'BusinessError' // Custom error name
208
216
  });
209
217
  }
210
218
  }
@@ -233,7 +241,8 @@ const examplePlugin = () => {
233
241
  if (error.name === 'BusinessError') {
234
242
  // Handle custom business errors
235
243
  console.error(`Business Error: ${error.message}`);
236
- } else if (error.status === 401) {
244
+ }
245
+ else if (error.status === 401) {
237
246
  // Handle unauthorized error
238
247
  console.error('Login has expired, please log in again');
239
248
  // window.location.href = '/login';
@@ -248,7 +257,7 @@ const examplePlugin = () => {
248
257
  console.log(`Request to ${config.url} completed`);
249
258
  }
250
259
  };
251
- };
260
+ }
252
261
  ```
253
262
 
254
263
  All lifecycle hooks support both synchronous and asynchronous operations. They can return either a Promise or a direct value. Each hook function receives the current configuration object (config), which can be used to make decisions and handle different request scenarios.
@@ -355,17 +364,13 @@ interface HookFetchPlugin<T = unknown, E = unknown, P = unknown, D = unknown> {
355
364
  }
356
365
  ```
357
366
 
358
-
359
-
360
-
361
-
362
367
  ## Vue Hooks
363
368
 
364
369
  Hook-Fetch provides Vue Composition API support, making it easier to use in Vue components:
365
370
 
366
371
  ```typescript
367
- import { useHookFetch } from 'hook-fetch/vue';
368
372
  import hookFetch from 'hook-fetch';
373
+ import { useHookFetch } from 'hook-fetch/vue';
369
374
 
370
375
  // Create request instance
371
376
  const api = hookFetch.create({
@@ -478,6 +483,7 @@ const YourComponent = () => {
478
483
  ```
479
484
 
480
485
  ### vscode hint plugin reference path
486
+
481
487
  ```typescript
482
488
  // Create a file hook-fetch.d.ts in src with the following content
483
489
  /// <reference types="hook-fetch/plugins" />
@@ -493,10 +499,12 @@ const YourComponent = () => {
493
499
  4. Plugins execute in order of priority.
494
500
 
495
501
  ## Upcoming Features
502
+
496
503
  - `umd` support
497
504
  - More plugin support
498
505
 
499
506
  ## 📝 Contribution Guide
507
+
500
508
  Feel free to submit `issues` or `pull requests` to help improve `Hook-Fetch`.
501
509
 
502
510
  ## 📄 License
package/README.md CHANGED
@@ -1,11 +1,18 @@
1
- # Hook-Fetch 🚀
1
+ <div align="center">
2
+ <a href="https://jsonlee12138.github.io/hook-fetch/"><img src="https://jsonlee12138.github.io/hook-fetch/img/logo.png" /></a><br>
3
+ </div>
4
+ <h1 align="center" style="margin-bottom: 0;">Hook-Fetch</h1>
5
+ <div align="center">
2
6
 
3
- **[English document](https://github.com/JsonLee12138/hook-fetch/blob/main/README.en.md)**
7
+ [![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=Release&logo=github&style=flat-square)](https://github.com/JsonLee12138/hook-fetch/actions/workflows/release.yml) [![install size](https://packagephobia.com/badge?p=hook-fetch)](https://packagephobia.com/result?p=hook-fetch) [![npm bundle size](https://img.shields.io/bundlephobia/minzip/hook-fetch?style=flat-square)](https://bundlephobia.com/package/hook-fetch@latest) [![npm downloads](https://img.shields.io/npm/dm/hook-fetch.svg?style=flat-square)](https://npm-stat.com/charts.html?package=hook-fetch) [![Discord](https://img.shields.io/badge/-Discord-5865F2?style=flat&logo=discord&logoColor=white)](https://discord.com/invite/666U6JTCQY)
4
8
 
5
- ## 介绍
9
+ **[English document](https://github.com/JsonLee12138/hook-fetch/blob/main/README.en.md)**
6
10
 
7
11
  Hook-Fetch 是一个强大的基于原生 fetch API 的请求库,提供了更简洁的语法、更丰富的功能和更灵活的插件系统。它支持请求重试、流式数据处理、中断请求等特性,并且采用Promise链式调用风格,使API请求变得更加简单和可控。
8
12
 
13
+ </div>
14
+ <br />
15
+
9
16
  ## 安装
10
17
 
11
18
  ```bash
@@ -149,7 +156,7 @@ Hook-Fetch 提供了强大的插件系统,可以在请求生命周期的各个
149
156
  ```typescript
150
157
  // 自定义插件示例:SSE文本解码插件
151
158
  // 当前只是示例, 建议使用当前库提供的`sseTextDecoderPlugin`插件, 那里做了更完善的处理
152
- const ssePlugin = () => {
159
+ function ssePlugin() {
153
160
  const decoder = new TextDecoder('utf-8');
154
161
  return {
155
162
  name: 'sse',
@@ -159,8 +166,8 @@ const ssePlugin = () => {
159
166
  }
160
167
  return chunk;
161
168
  }
162
- }
163
- };
169
+ };
170
+ }
164
171
 
165
172
  // 注册插件
166
173
  api.use(ssePlugin());
@@ -176,7 +183,7 @@ for await (const chunk of req.stream<string>()) {
176
183
 
177
184
  ```typescript
178
185
  // 完整的插件示例,展示各个生命周期的使用
179
- const examplePlugin = () => {
186
+ function examplePlugin() {
180
187
  return {
181
188
  name: 'example',
182
189
  priority: 1, // 优先级,数字越小优先级越高
@@ -194,17 +201,18 @@ const examplePlugin = () => {
194
201
  // 可以处理响应数据, context.result 是已经过 json() 等方法处理后的结果
195
202
  if (context.responseType === 'json') {
196
203
  // 例如,根据后端的业务码判断请求是否真正成功
197
- if(context.result.code === 200){
204
+ if (context.result.code === 200) {
198
205
  // 业务成功,直接返回 context
199
- return context
200
- }else{
206
+ return context;
207
+ }
208
+ else {
201
209
  // 业务失败,主动抛出一个 ResponseError,它将在 onError 钩子中被捕获
202
210
  throw new ResponseError({
203
211
  message: context.result.message, // 使用后端的错误信息
204
- status: context.result.code, // 使用后端的业务码作为状态
205
- response: context.response, // 原始 Response 对象
212
+ status: context.result.code, // 使用后端的业务码作为状态
213
+ response: context.response, // 原始 Response 对象
206
214
  config: context.config,
207
- name: 'BusinessError' // 自定义错误名称
215
+ name: 'BusinessError' // 自定义错误名称
208
216
  });
209
217
  }
210
218
  }
@@ -233,7 +241,8 @@ const examplePlugin = () => {
233
241
  if (error.name === 'BusinessError') {
234
242
  // 处理自定义的业务错误
235
243
  console.error(`业务错误: ${error.message}`);
236
- } else if (error.status === 401) {
244
+ }
245
+ else if (error.status === 401) {
237
246
  // 处理未授权错误
238
247
  console.error('登录已过期,请重新登录');
239
248
  // window.location.href = '/login';
@@ -248,14 +257,14 @@ const examplePlugin = () => {
248
257
  console.log(`Request to ${config.url} completed`);
249
258
  }
250
259
  };
251
- };
260
+ }
252
261
  ```
253
262
 
254
263
  #### 业务场景封装示例
255
264
 
256
265
  ```typescript
257
266
  // 创建一个业务请求实例
258
- const createRequest = () => {
267
+ function createRequest() {
259
268
  // 创建基础实例
260
269
  const request = hookFetch.create({
261
270
  baseURL: 'https://api.example.com',
@@ -322,24 +331,24 @@ const createRequest = () => {
322
331
  return {
323
332
  // 用户相关接口
324
333
  user: {
325
- // 获取用户信息
326
- getInfo: () => request.get('/user/info').json(),
327
- // 更新用户信息
328
- updateInfo: (data) => request.put('/user/info', data).json(),
329
- // 修改密码
330
- changePassword: (data) => request.post('/user/password', data).json()
334
+ // 获取用户信息
335
+ getInfo: () => request.get('/user/info').json(),
336
+ // 更新用户信息
337
+ updateInfo: data => request.put('/user/info', data).json(),
338
+ // 修改密码
339
+ changePassword: data => request.post('/user/password', data).json()
331
340
  },
332
341
  // 订单相关接口
333
342
  order: {
334
343
  // 获取订单列表
335
- getList: (params) => request.get('/orders', params).json(),
344
+ getList: params => request.get('/orders', params).json(),
336
345
  // 创建订单
337
- create: (data) => request.post('/orders', data).json(),
346
+ create: data => request.post('/orders', data).json(),
338
347
  // 取消订单
339
- cancel: (id) => request.post(`/orders/${id}/cancel`).json()
348
+ cancel: id => request.post(`/orders/${id}/cancel`).json()
340
349
  }
341
350
  };
342
- };
351
+ }
343
352
 
344
353
  // 使用示例
345
354
  const api = createRequest();
@@ -355,6 +364,7 @@ const order = await api.order.create({
355
364
  ```
356
365
 
357
366
  插件钩子函数:
367
+
358
368
  - `beforeRequest`: 请求发送前处理配置,可以返回新的配置或直接修改配置
359
369
  - `afterResponse`: 响应接收后处理数据,可以返回新的响应或直接修改响应
360
370
  - `beforeStream`: 流式请求开始时的处理,用于初始化或转换流
@@ -466,14 +476,13 @@ interface HookFetchPlugin<T = unknown, E = unknown, P = unknown, D = unknown> {
466
476
  }
467
477
  ```
468
478
 
469
-
470
479
  ## Vue Hooks
471
480
 
472
481
  Hook-Fetch 提供了 Vue 组合式 API 的支持,可以更方便地在 Vue 组件中使用:
473
482
 
474
483
  ```typescript
475
- import { useHookFetch } from 'hook-fetch/vue';
476
484
  import hookFetch from 'hook-fetch';
485
+ import { useHookFetch } from 'hook-fetch/vue';
477
486
 
478
487
  // 创建请求实例
479
488
  const api = hookFetch.create({
@@ -586,6 +595,7 @@ const YourComponent = () => {
586
595
  ```
587
596
 
588
597
  ### vscode提示插件的引用路径
598
+
589
599
  ```typescript
590
600
  // 在 src 中创建文件 hook-fetch.d.ts, 内容如下
591
601
  /// <reference types="hook-fetch/plugins" />
@@ -601,10 +611,12 @@ const YourComponent = () => {
601
611
  4. 插件按照优先级顺序执行
602
612
 
603
613
  ## 预计开发内容
614
+
604
615
  - `umd` 支持
605
616
  - 更多的插件支持
606
617
 
607
618
  ## 📝 贡献指南
619
+
608
620
  欢迎提交`issue`或`pull request`,共同完善`Hook-Fetch`。
609
621
 
610
622
  ## 📄 许可证