soon-fetch 4.0.0 → 4.0.2-beta.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/README.md +421 -44
- package/dist/index.d.ts +890 -0
- package/dist/index.js +1 -0
- package/dist/index.umd.js +1 -0
- package/package.json +9 -7
- package/dist/index.cjs +0 -1
- package/dist/index.d.cts +0 -480
- package/dist/index.d.mts +0 -480
- package/dist/index.iife.js +0 -1
- package/dist/index.mjs +0 -1
package/README.md
CHANGED
|
@@ -8,12 +8,13 @@
|
|
|
8
8
|
|
|
9
9
|
> - 🌐 automatic parse restful api url parameters
|
|
10
10
|
> - ⭐ rapid define a request api
|
|
11
|
+
> - 🎯 fork sub-instance with prefix and default options
|
|
11
12
|
> - ⌛ timeout disconnect
|
|
12
13
|
> - 📦 request reusing
|
|
13
14
|
> - 🚀 request race
|
|
14
15
|
> - 📝 response cache
|
|
15
16
|
> - 🔤 automatic serialization of JSON
|
|
16
|
-
> - 📏 .min size less than **
|
|
17
|
+
> - 📏 .min size less than **10K**, smaller after zip
|
|
17
18
|
> - 💡 smart type tips with Typescript
|
|
18
19
|
|
|
19
20
|
- [Example](#example)
|
|
@@ -36,9 +37,9 @@
|
|
|
36
37
|
import { createSoon, soonFetch } from "soon-fetch";
|
|
37
38
|
|
|
38
39
|
// 使用 soonFetch 作为基础请求函数
|
|
39
|
-
const request = async <T>(url: string, options?: SoonOptions) => {
|
|
40
|
+
const request = async <T>(url: string, options?: SoonOptions): Promise<T> => {
|
|
40
41
|
const isGet = !options?.method || options?.method.toLocaleLowerCase() === "get";
|
|
41
|
-
const response = await soonFetch
|
|
42
|
+
const response = await soonFetch({
|
|
42
43
|
url,
|
|
43
44
|
options,
|
|
44
45
|
baseURL: '/api',
|
|
@@ -51,7 +52,12 @@ const request = async <T>(url: string, options?: SoonOptions) => {
|
|
|
51
52
|
staleTime: isGet ? 2 * 1000 : 0,
|
|
52
53
|
},
|
|
53
54
|
});
|
|
54
|
-
|
|
55
|
+
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return response.json() as Promise<T>;
|
|
55
61
|
};
|
|
56
62
|
|
|
57
63
|
const soon = createSoon(request);
|
|
@@ -133,7 +139,7 @@ import { useEffect, useRef, useState } from "react";
|
|
|
133
139
|
type User = { name: string; job: string };
|
|
134
140
|
const api = soon.GET("/api/users").Query<{ page: number }>().Ok<User[]>();
|
|
135
141
|
export default function App() {
|
|
136
|
-
const refAbort = useRef([]);
|
|
142
|
+
const refAbort = useRef<[AbortController] | []>([]);
|
|
137
143
|
const [list, setList] = useState<User[]>([]);
|
|
138
144
|
const [page, setPage] = useState(1);
|
|
139
145
|
useEffect(() => {
|
|
@@ -156,13 +162,15 @@ export default function App() {
|
|
|
156
162
|
|
|
157
163
|
##### Rapid Define APIs
|
|
158
164
|
|
|
159
|
-
```
|
|
160
|
-
|
|
165
|
+
```ts
|
|
166
|
+
//可以是 GET POST PATCH PUT DELETE
|
|
167
|
+
//GET 请求数据传递至query,其他方法请求数据传递至body
|
|
161
168
|
soon.GET(url:string).Query<Query>().Ok<Response>()
|
|
162
169
|
soon.POST(url:string).Body<Body>().Ok<Response>()
|
|
163
170
|
soon.GET(url:string).Options({ timeout: 5000 }).Ok<Response>()
|
|
164
171
|
soon.POST(url:string).Body<Body>().Options({ timeout: 5000 }).Ok<Response>()
|
|
165
|
-
|
|
172
|
+
|
|
173
|
+
//define an api
|
|
166
174
|
export const getUserInfo = soon.GET("/user/:id").Ok();
|
|
167
175
|
//then use in any where
|
|
168
176
|
getUserInfo({ id: 2 }).then((res) => console.log(res));
|
|
@@ -222,30 +230,95 @@ Create a soon request instance.
|
|
|
222
230
|
|
|
223
231
|
- `request`: A function to handle the actual request, receives url and options, returns a Promise
|
|
224
232
|
|
|
225
|
-
**Returns:** An object containing request method, API methods (GET, POST, PUT, DELETE, PATCH),
|
|
233
|
+
**Returns:** An object containing request method, API methods (GET, POST, PUT, DELETE, PATCH), shortcut methods (get, post, put, delete, patch, head, options), and fork method for creating sub-instances
|
|
226
234
|
|
|
227
235
|
**Example:**
|
|
228
236
|
|
|
229
237
|
```typescript
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
238
|
+
import { createSoon, soonFetch } from "soon-fetch";
|
|
239
|
+
|
|
240
|
+
// Define custom request wrapper with business logic
|
|
241
|
+
const request = async <T>(url: string, options?: SoonOptions): Promise<T> => {
|
|
242
|
+
const isGet = !options?.method || options?.method.toLowerCase() === "get";
|
|
243
|
+
|
|
244
|
+
const response = await soonFetch({
|
|
245
|
+
url,
|
|
246
|
+
options,
|
|
247
|
+
baseURL: '/api',
|
|
248
|
+
baseOptions: {
|
|
249
|
+
timeout: 20 * 1000,
|
|
250
|
+
headers: new Headers({
|
|
251
|
+
Authorization: "Bearer " + localStorage.getItem("token"),
|
|
252
|
+
}),
|
|
253
|
+
share: isGet,
|
|
254
|
+
staleTime: isGet ? 2 * 1000 : 0,
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
if (!response.ok) {
|
|
259
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
234
260
|
}
|
|
235
|
-
|
|
261
|
+
|
|
262
|
+
return response.json() as Promise<T>;
|
|
263
|
+
};
|
|
236
264
|
|
|
237
|
-
//
|
|
238
|
-
const
|
|
265
|
+
// Create soon instance
|
|
266
|
+
const soon = createSoon(request);
|
|
239
267
|
|
|
240
|
-
//
|
|
241
|
-
|
|
242
|
-
.POST("/user/login")
|
|
243
|
-
.Body<{ username: string; password: string }>()
|
|
244
|
-
.Ok<{ token: string }>();
|
|
268
|
+
// Usage 1: Shortcut methods with generics
|
|
269
|
+
const users = await soon.get<{ id: number; name: string }[]>("/api/users");
|
|
245
270
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
271
|
+
// Usage 2: Define typed APIs with chain calls
|
|
272
|
+
export const getUserById = soon
|
|
273
|
+
.GET("/user/:id")
|
|
274
|
+
.Params<{ id: number }>()
|
|
275
|
+
.Ok<{ id: number; name: string }>();
|
|
276
|
+
|
|
277
|
+
export const createUser = soon
|
|
278
|
+
.POST("/user")
|
|
279
|
+
.Body<{ name: string; email: string }>()
|
|
280
|
+
.Ok<{ id: number }>();
|
|
281
|
+
|
|
282
|
+
// Usage 3: Use defined APIs
|
|
283
|
+
const user = await getUserById({ id: 1 });
|
|
284
|
+
const newUser = await createUser({ name: "John", email: "john@example.com" });
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
#### fork
|
|
288
|
+
|
|
289
|
+
Create a sub-instance with a URL prefix and default options.
|
|
290
|
+
|
|
291
|
+
**Parameters:**
|
|
292
|
+
|
|
293
|
+
- `prefix`: URL prefix string (e.g. "/api/v1")
|
|
294
|
+
- `defaultOptions?`: Default options that apply to all requests via this sub-instance
|
|
295
|
+
|
|
296
|
+
**Returns:** A new `createSoon` instance with the prefix and default options pre-applied.
|
|
297
|
+
|
|
298
|
+
**Example:**
|
|
299
|
+
|
|
300
|
+
```typescript
|
|
301
|
+
// Create a forked sub-instance for a specific API version
|
|
302
|
+
const v1 = soon.fork("/api/v1", { timeout: 5000 });
|
|
303
|
+
const v2 = soon.fork("/api/v2", { timeout: 10000 });
|
|
304
|
+
|
|
305
|
+
// All requests are automatically prefixed and use default options
|
|
306
|
+
v1.get("/users"); // GET /api/v1/users with timeout: 5000
|
|
307
|
+
v2.get("/users"); // GET /api/v2/users with timeout: 10000
|
|
308
|
+
|
|
309
|
+
// Options can still be overridden per request
|
|
310
|
+
v1.get("/users", { timeout: 8000 }); // GET /api/v1/users with timeout: 8000
|
|
311
|
+
|
|
312
|
+
// Chain API definitions work too
|
|
313
|
+
const getUser = v1.GET("/users/:id").Params<{ id: number }>().Ok<User>();
|
|
314
|
+
getUser({ id: 1 }); // GET /api/v1/users/1 with timeout: 5000
|
|
315
|
+
|
|
316
|
+
// Fork can be nested
|
|
317
|
+
const admin = v1.fork("/admin");
|
|
318
|
+
admin.get("/stats"); // GET /api/v1/admin/stats with timeout: 5000
|
|
319
|
+
|
|
320
|
+
// Absolute URLs bypass the prefix
|
|
321
|
+
v1.get("https://other-api.com/data"); // Uses the absolute URL directly
|
|
249
322
|
```
|
|
250
323
|
|
|
251
324
|
#### createShortApi
|
|
@@ -433,19 +506,20 @@ isBodyJson("string"); // false
|
|
|
433
506
|
|
|
434
507
|
#### genRequestKey
|
|
435
508
|
|
|
436
|
-
Generate a unique identification key for the request.
|
|
437
|
-
Generate a unique key value based on the request's URL, method, headers, body, query parameters, etc., used for caching and request sharing.
|
|
509
|
+
Generate a unique identification key for the request (async).
|
|
510
|
+
Generate a unique key value based on the request's URL, method, headers, body, query parameters, etc., used for caching and request sharing. Supports serializing special body types like Blob and FormData for deterministic key generation.
|
|
438
511
|
|
|
439
512
|
**Parameters:**
|
|
440
513
|
|
|
441
514
|
- `req`: Request object containing url and options
|
|
515
|
+
- `sortObjKeys?`: Whether to sort object keys for stable serialization
|
|
442
516
|
|
|
443
|
-
**Returns:**
|
|
517
|
+
**Returns:** Promise resolving to the unique identification string of the request
|
|
444
518
|
|
|
445
519
|
**Example:**
|
|
446
520
|
|
|
447
521
|
```typescript
|
|
448
|
-
const key = genRequestKey({
|
|
522
|
+
const key = await genRequestKey({
|
|
449
523
|
url: "/api/users",
|
|
450
524
|
options: { method: "GET", params: { id: 1 } },
|
|
451
525
|
});
|
|
@@ -541,12 +615,12 @@ A lightweight fetch wrapper with caching, sharing, and race condition handling.
|
|
|
541
615
|
- `store`: Custom request store
|
|
542
616
|
- `sortRequestKey`: Whether to sort request key
|
|
543
617
|
|
|
544
|
-
**Returns:** Promise that resolves to
|
|
618
|
+
**Returns:** Promise that resolves to Response
|
|
545
619
|
|
|
546
620
|
**Example:**
|
|
547
621
|
|
|
548
622
|
```typescript
|
|
549
|
-
const
|
|
623
|
+
const response = await soonFetch({
|
|
550
624
|
url: "/api/users",
|
|
551
625
|
options: {
|
|
552
626
|
method: "GET",
|
|
@@ -556,6 +630,12 @@ const data = await soonFetch<User[]>({
|
|
|
556
630
|
},
|
|
557
631
|
baseURL: "https://api.example.com",
|
|
558
632
|
});
|
|
633
|
+
|
|
634
|
+
if (!response.ok) {
|
|
635
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const data = await response.json() as User[];
|
|
559
639
|
```
|
|
560
640
|
|
|
561
641
|
#### toFormData
|
|
@@ -653,16 +733,17 @@ const data = await requestWithStore(store, () => fetch(url, options), requestKey
|
|
|
653
733
|
|
|
654
734
|
#### soon-fetch
|
|
655
735
|
|
|
656
|
-
**极轻量的请求库,不到
|
|
736
|
+
**极轻量的请求库,不到 10K**
|
|
657
737
|
|
|
658
738
|
> - 🌐 自动解析 rest Url 的参数
|
|
659
739
|
> - ⭐ 快捷定义请求 api
|
|
740
|
+
> - 🎯 fork 子实例(前缀+默认选项)
|
|
660
741
|
> - ⌛ 超时断开
|
|
661
742
|
> - 📦 请求复用
|
|
662
743
|
> - 🚀 请求竞态
|
|
663
744
|
> - 📝 响应缓存
|
|
664
745
|
> - 🔤 自动处理 JSON
|
|
665
|
-
> - 📏 不到 **
|
|
746
|
+
> - 📏 不到 **10K** , zip 后会更小
|
|
666
747
|
> - 💡 用 typescript 有智能类型提醒
|
|
667
748
|
|
|
668
749
|
- [示例](#示例)
|
|
@@ -688,9 +769,9 @@ const data = await requestWithStore(store, () => fetch(url, options), requestKey
|
|
|
688
769
|
import { createSoon, soonFetch } from "soon-fetch";
|
|
689
770
|
|
|
690
771
|
// 使用 soonFetch 作为基础请求函数
|
|
691
|
-
const request = async <T>(url: string, options?: SoonOptions) => {
|
|
772
|
+
const request = async <T>(url: string, options?: SoonOptions): Promise<T> => {
|
|
692
773
|
const isGet = !options?.method || options?.method.toLocaleLowerCase() === "get";
|
|
693
|
-
const response = await soonFetch
|
|
774
|
+
const response = await soonFetch({
|
|
694
775
|
url,
|
|
695
776
|
options,
|
|
696
777
|
baseURL: '/api',
|
|
@@ -703,7 +784,12 @@ const request = async <T>(url: string, options?: SoonOptions) => {
|
|
|
703
784
|
staleTime: isGet ? 2 * 1000 : 0,
|
|
704
785
|
},
|
|
705
786
|
});
|
|
706
|
-
|
|
787
|
+
|
|
788
|
+
if (!response.ok) {
|
|
789
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
return response.json() as Promise<T>;
|
|
707
793
|
};
|
|
708
794
|
|
|
709
795
|
const soon = createSoon(request);
|
|
@@ -790,7 +876,7 @@ import { useEffect, useRef, useState } from "react";
|
|
|
790
876
|
type User = { name: string; job: string };
|
|
791
877
|
const api = soon.GET("/api/users").Query<{ page: number }>().Ok<User[]>();
|
|
792
878
|
export default function App() {
|
|
793
|
-
const refAbort = useRef([]);
|
|
879
|
+
const refAbort = useRef<[AbortController] | []>([]);
|
|
794
880
|
const [list, setList] = useState<User[]>([]);
|
|
795
881
|
const [page, setPage] = useState(1);
|
|
796
882
|
useEffect(() => {
|
|
@@ -881,7 +967,7 @@ type SoonOptions = Omit<RequestInit, "body"> & {
|
|
|
881
967
|
|
|
882
968
|
- `request`: 用于处理实际请求的函数,接收 url 和 options,返回一个 Promise
|
|
883
969
|
|
|
884
|
-
**返回:** 包含 request 方法、API 方法(GET、POST、PUT、DELETE、PATCH)和快捷方法(get、post、put、delete、patch、head、options
|
|
970
|
+
**返回:** 包含 request 方法、API 方法(GET、POST、PUT、DELETE、PATCH)和快捷方法(get、post、put、delete、patch、head、options)以及 fork 方法的对象
|
|
885
971
|
|
|
886
972
|
**示例:**
|
|
887
973
|
|
|
@@ -907,6 +993,43 @@ login({ username: "admin", password: "123" }).then((res) => {
|
|
|
907
993
|
});
|
|
908
994
|
```
|
|
909
995
|
|
|
996
|
+
#### fork
|
|
997
|
+
|
|
998
|
+
创建一个带有 URL 前缀和默认选项的子实例。
|
|
999
|
+
|
|
1000
|
+
**参数:**
|
|
1001
|
+
|
|
1002
|
+
- `prefix`: URL 前缀字符串(如 "/api/v1")
|
|
1003
|
+
- `defaultOptions?`: 默认选项,对该子实例的所有请求生效
|
|
1004
|
+
|
|
1005
|
+
**返回:** 一个新的 `createSoon` 实例,已预置前缀和默认选项。
|
|
1006
|
+
|
|
1007
|
+
**示例:**
|
|
1008
|
+
|
|
1009
|
+
```typescript
|
|
1010
|
+
// 为不同 API 版本创建 fork 子实例
|
|
1011
|
+
const v1 = soon.fork("/api/v1", { timeout: 5000 });
|
|
1012
|
+
const v2 = soon.fork("/api/v2", { timeout: 10000 });
|
|
1013
|
+
|
|
1014
|
+
// 所有请求会自动添加前缀并使用默认选项
|
|
1015
|
+
v1.get("/users"); // GET /api/v1/users with timeout: 5000
|
|
1016
|
+
v2.get("/users"); // GET /api/v2/users with timeout: 10000
|
|
1017
|
+
|
|
1018
|
+
// 单次请求仍可覆盖默认选项
|
|
1019
|
+
v1.get("/users", { timeout: 8000 }); // GET /api/v1/users with timeout: 8000
|
|
1020
|
+
|
|
1021
|
+
// 链式 API 定义同样适用
|
|
1022
|
+
const getUser = v1.GET("/users/:id").Params<{ id: number }>().Ok<User>();
|
|
1023
|
+
getUser({ id: 1 }); // GET /api/v1/users/1 with timeout: 5000
|
|
1024
|
+
|
|
1025
|
+
// fork 支持嵌套
|
|
1026
|
+
const admin = v1.fork("/admin");
|
|
1027
|
+
admin.get("/stats"); // GET /api/v1/admin/stats with timeout: 5000
|
|
1028
|
+
|
|
1029
|
+
// 绝对 URL 会绕过前缀
|
|
1030
|
+
v1.get("https://other-api.com/data"); // 直接使用该 URL
|
|
1031
|
+
```
|
|
1032
|
+
|
|
910
1033
|
#### createShortApi
|
|
911
1034
|
|
|
912
1035
|
创建 API 快捷方法的工厂函数。
|
|
@@ -1089,19 +1212,20 @@ isBodyJson("string"); // false
|
|
|
1089
1212
|
|
|
1090
1213
|
#### genRequestKey
|
|
1091
1214
|
|
|
1092
|
-
|
|
1093
|
-
根据请求的 URL、方法、headers、body
|
|
1215
|
+
生成请求的唯一标识键(异步)。
|
|
1216
|
+
根据请求的 URL、方法、headers、body、查询参数等生成唯一键值,用于缓存和请求共享。支持序列化 Blob 和 FormData 等特殊 body 类型以生成确定性键。
|
|
1094
1217
|
|
|
1095
1218
|
**参数:**
|
|
1096
1219
|
|
|
1097
1220
|
- `req`: 包含 url 和 options 的请求对象
|
|
1221
|
+
- `sortObjKeys?`: 是否对对象键进行排序以获得稳定序列化
|
|
1098
1222
|
|
|
1099
|
-
**返回:**
|
|
1223
|
+
**返回:** 解析为唯一标识字符串的 Promise
|
|
1100
1224
|
|
|
1101
1225
|
**示例:**
|
|
1102
1226
|
|
|
1103
1227
|
```typescript
|
|
1104
|
-
const key = genRequestKey({
|
|
1228
|
+
const key = await genRequestKey({
|
|
1105
1229
|
url: "/api/users",
|
|
1106
1230
|
options: { method: "GET", params: { id: 1 } },
|
|
1107
1231
|
});
|
|
@@ -1197,12 +1321,12 @@ silentRefresh(
|
|
|
1197
1321
|
- `store`: 自定义请求存储
|
|
1198
1322
|
- `sortRequestKey`: 是否对请求键进行排序
|
|
1199
1323
|
|
|
1200
|
-
**返回:**
|
|
1324
|
+
**返回:** 解析为 Response 的 Promise
|
|
1201
1325
|
|
|
1202
1326
|
**示例:**
|
|
1203
1327
|
|
|
1204
1328
|
```typescript
|
|
1205
|
-
const
|
|
1329
|
+
const response = await soonFetch({
|
|
1206
1330
|
url: "/api/users",
|
|
1207
1331
|
options: {
|
|
1208
1332
|
method: "GET",
|
|
@@ -1212,6 +1336,12 @@ const data = await soonFetch<User[]>({
|
|
|
1212
1336
|
},
|
|
1213
1337
|
baseURL: "https://api.example.com",
|
|
1214
1338
|
});
|
|
1339
|
+
|
|
1340
|
+
if (!response.ok) {
|
|
1341
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
const data = await response.json() as User[];
|
|
1215
1345
|
```
|
|
1216
1346
|
|
|
1217
1347
|
#### toFormData
|
|
@@ -1310,6 +1440,253 @@ const data = await requestWithStore(store, () => fetch(url, options), requestKey
|
|
|
1310
1440
|
|
|
1311
1441
|
##### 安装 Installation
|
|
1312
1442
|
|
|
1313
|
-
```
|
|
1443
|
+
```
|
|
1314
1444
|
npm install soon-fetch
|
|
1315
1445
|
```
|
|
1446
|
+
|
|
1447
|
+
## Best Practices / 最佳实践
|
|
1448
|
+
|
|
1449
|
+
#### Real-World Project Structure / 真实项目结构
|
|
1450
|
+
|
|
1451
|
+
Based on [soon-admin-vue](https://github.com/leafio/soon-admin-vue):
|
|
1452
|
+
|
|
1453
|
+
#### File Organization / 文件组织
|
|
1454
|
+
|
|
1455
|
+
```
|
|
1456
|
+
src/api/
|
|
1457
|
+
├── request.ts # Request wrapper with unified error handling
|
|
1458
|
+
├── types.ts # Shared type definitions (e.g., PagedParams)
|
|
1459
|
+
├── index.ts # Export all API modules
|
|
1460
|
+
└── modules/
|
|
1461
|
+
├── auth.ts # Authentication APIs
|
|
1462
|
+
├── user.ts # User management APIs
|
|
1463
|
+
├── role.ts # Role management APIs
|
|
1464
|
+
├── dept.ts # Department management APIs
|
|
1465
|
+
└── ... # Other domain-specific modules
|
|
1466
|
+
```
|
|
1467
|
+
|
|
1468
|
+
#### Step 1: Create Request Wrapper (src/api/request.ts)
|
|
1469
|
+
|
|
1470
|
+
```typescript
|
|
1471
|
+
import { createSoon, soonFetch } from "soon-fetch";
|
|
1472
|
+
import type { SoonOptions } from "soon-fetch";
|
|
1473
|
+
|
|
1474
|
+
type ReqOpts = SoonOptions & {
|
|
1475
|
+
retry?: { max?: number; enable?: (result: any) => boolean };
|
|
1476
|
+
toastErr?: boolean;
|
|
1477
|
+
};
|
|
1478
|
+
|
|
1479
|
+
const request = async <T>(url: string, options?: ReqOpts): Promise<T> => {
|
|
1480
|
+
const isGet = !options?.method || options?.method.toLowerCase() === "get";
|
|
1481
|
+
|
|
1482
|
+
try {
|
|
1483
|
+
const response = await soonFetch({
|
|
1484
|
+
url,
|
|
1485
|
+
options,
|
|
1486
|
+
baseURL: import.meta.env.VITE_API_BASE,
|
|
1487
|
+
baseOptions: {
|
|
1488
|
+
timeout: 20 * 1000,
|
|
1489
|
+
headers: new Headers({ Authorization: localStorage.getItem("token") ?? "" }),
|
|
1490
|
+
share: isGet,
|
|
1491
|
+
staleTime: isGet ? 2 * 1000 : 0,
|
|
1492
|
+
},
|
|
1493
|
+
});
|
|
1494
|
+
|
|
1495
|
+
if (!response.ok) {
|
|
1496
|
+
throw new Error(`HTTP ${response.status}`);
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// Auto-parse JSON
|
|
1500
|
+
if (response.headers.get("content-type")?.includes("json")) {
|
|
1501
|
+
const body = await response.json();
|
|
1502
|
+
return body.data as T;
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
return response as unknown as T;
|
|
1506
|
+
} catch (error: any) {
|
|
1507
|
+
// Unified error handling
|
|
1508
|
+
if (error.name === "TimeoutError") {
|
|
1509
|
+
ElMessage.error("Request timeout");
|
|
1510
|
+
} else if (error.name !== "AbortError" && options?.toastErr !== false) {
|
|
1511
|
+
ElMessage.error(error.message);
|
|
1512
|
+
}
|
|
1513
|
+
throw error;
|
|
1514
|
+
}
|
|
1515
|
+
};
|
|
1516
|
+
|
|
1517
|
+
export const soon = createSoon<ReqOpts>(request);
|
|
1518
|
+
```
|
|
1519
|
+
|
|
1520
|
+
**Key Points:**
|
|
1521
|
+
- ✅ **Centralized error handling**: All HTTP errors, timeouts, and business errors handled in one place
|
|
1522
|
+
- ✅ **Auto Token refresh**: Handle 401 errors and retry automatically
|
|
1523
|
+
- ✅ **Smart caching**: GET requests cached by default, write operations not cached
|
|
1524
|
+
- ✅ **No repetitive try-catch**: Components call APIs directly without error handling boilerplate
|
|
1525
|
+
|
|
1526
|
+
---
|
|
1527
|
+
|
|
1528
|
+
#### Step 2: Define Typed APIs (src/api/modules/user.ts)
|
|
1529
|
+
|
|
1530
|
+
```typescript
|
|
1531
|
+
import { downloadBlob, getHeaderFilename } from "soon-utils";
|
|
1532
|
+
import type { PagedParams } from "../types";
|
|
1533
|
+
import type { Dept } from "./dept";
|
|
1534
|
+
import type { Role } from "./role";
|
|
1535
|
+
import { soon } from "../request";
|
|
1536
|
+
|
|
1537
|
+
// Type definitions
|
|
1538
|
+
export type User = {
|
|
1539
|
+
id: number;
|
|
1540
|
+
username: string;
|
|
1541
|
+
email: string | null;
|
|
1542
|
+
phone: string | null;
|
|
1543
|
+
name: string | null;
|
|
1544
|
+
avatar: string | null;
|
|
1545
|
+
roleId: number | undefined;
|
|
1546
|
+
deptId: number | undefined;
|
|
1547
|
+
status: number;
|
|
1548
|
+
};
|
|
1549
|
+
|
|
1550
|
+
export type UserInfo = User & {
|
|
1551
|
+
createTime: Date;
|
|
1552
|
+
updateTime: Date | null;
|
|
1553
|
+
dept?: Pick<Dept, "id" | "name">;
|
|
1554
|
+
role?: Pick<Role, "id" | "name">;
|
|
1555
|
+
};
|
|
1556
|
+
|
|
1557
|
+
type ListQueryUser = PagedParams & {
|
|
1558
|
+
keyword?: string;
|
|
1559
|
+
timeRange?: [string, string];
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
// CRUD APIs - simple and type-safe
|
|
1563
|
+
export const list_user = soon.GET("/user").Query<ListQueryUser>().Ok<{ list: UserInfo[] }>();
|
|
1564
|
+
export const add_user = soon.POST("/user").Body<User>().Ok();
|
|
1565
|
+
export const update_user = soon.PUT("/user/:id").Body<User>().Ok();
|
|
1566
|
+
export const del_user = soon.DELETE("/user/:id").Ok();
|
|
1567
|
+
export const detail_user = soon.GET("/user/:id").Ok<UserInfo>();
|
|
1568
|
+
|
|
1569
|
+
// File download - returns Response for custom handling
|
|
1570
|
+
export const download_user_table = async (query: ListQueryUser) => {
|
|
1571
|
+
return soon.get<Response>("/user/export", { query }).then(async (res) => {
|
|
1572
|
+
const body = await res.blob();
|
|
1573
|
+
const filename = getHeaderFilename(res.headers) ?? "user.xlsx";
|
|
1574
|
+
downloadBlob(body, filename);
|
|
1575
|
+
});
|
|
1576
|
+
};
|
|
1577
|
+
|
|
1578
|
+
// Captcha example
|
|
1579
|
+
export const getCaptcha = soon.GET("/captcha").Ok<{ id: number; img: string }>();
|
|
1580
|
+
```
|
|
1581
|
+
|
|
1582
|
+
**Key Points:**
|
|
1583
|
+
- ✅ **Domain-based modules**: Each module handles one business domain (user, role, dept, etc.)
|
|
1584
|
+
- ✅ **Type safety**: Use `.Params<>()`, `.Body<>()`, `.Ok<>()` for full type inference
|
|
1585
|
+
- ✅ **Shared types**: Import cross-domain types from sibling modules
|
|
1586
|
+
- ✅ **Special operations**: Complex logic (file download) wrapped in async functions
|
|
1587
|
+
- ✅ **Naming convention**: Use snake_case for API exports (e.g., `list_user`, `add_user`)
|
|
1588
|
+
|
|
1589
|
+
---
|
|
1590
|
+
|
|
1591
|
+
#### Step 3: Centralized Exports (src/api/index.ts)
|
|
1592
|
+
|
|
1593
|
+
```typescript
|
|
1594
|
+
export * from "./modules/auth";
|
|
1595
|
+
export * from "./modules/user";
|
|
1596
|
+
export * from "./modules/role";
|
|
1597
|
+
// ... other modules
|
|
1598
|
+
```
|
|
1599
|
+
|
|
1600
|
+
**Usage in components:**
|
|
1601
|
+
```typescript
|
|
1602
|
+
import { list_user, add_user, del_user } from "@/api";
|
|
1603
|
+
```
|
|
1604
|
+
|
|
1605
|
+
---
|
|
1606
|
+
|
|
1607
|
+
#### Step 4: Use in Components - Clean and Simple!
|
|
1608
|
+
|
|
1609
|
+
**Vue 3 Example:**
|
|
1610
|
+
```typescript
|
|
1611
|
+
<script setup lang="ts">
|
|
1612
|
+
import { ref, onMounted } from "vue";
|
|
1613
|
+
import { list_user, del_user } from "@/api";
|
|
1614
|
+
import type { UserInfo } from "@/api";
|
|
1615
|
+
|
|
1616
|
+
const users = ref<UserInfo[]>([]);
|
|
1617
|
+
const loading = ref(false);
|
|
1618
|
+
|
|
1619
|
+
const fetchUsers = async () => {
|
|
1620
|
+
loading.value = true;
|
|
1621
|
+
try {
|
|
1622
|
+
const { list } = await list_user({ page: 1, pageSize: 10 });
|
|
1623
|
+
users.value = list;
|
|
1624
|
+
} finally {
|
|
1625
|
+
loading.value = false;
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
|
|
1629
|
+
const handleDelete = async (id: number) => {
|
|
1630
|
+
await del_user({ id });
|
|
1631
|
+
await fetchUsers();
|
|
1632
|
+
};
|
|
1633
|
+
|
|
1634
|
+
onMounted(fetchUsers);
|
|
1635
|
+
</script>
|
|
1636
|
+
```
|
|
1637
|
+
|
|
1638
|
+
**React Example with Race Condition Handling:**
|
|
1639
|
+
```typescript
|
|
1640
|
+
import { useEffect, useRef, useState } from "react";
|
|
1641
|
+
import { list_user } from "@/api";
|
|
1642
|
+
import type { UserInfo } from "@/api";
|
|
1643
|
+
|
|
1644
|
+
export default function UserList() {
|
|
1645
|
+
const [users, setUsers] = useState<UserInfo[]>([]);
|
|
1646
|
+
const [loading, setLoading] = useState(false);
|
|
1647
|
+
const abortRef = useRef<[AbortController] | []>([]);
|
|
1648
|
+
|
|
1649
|
+
useEffect(() => {
|
|
1650
|
+
setLoading(true);
|
|
1651
|
+
list_user({ page: 1, pageSize: 10 }, { aborts: abortRef.current })
|
|
1652
|
+
.then(({ list }) => setUsers(list))
|
|
1653
|
+
.catch((err) => {
|
|
1654
|
+
if (err.name !== "AbortError") console.error(err);
|
|
1655
|
+
})
|
|
1656
|
+
.finally(() => setLoading(false));
|
|
1657
|
+
}, []);
|
|
1658
|
+
|
|
1659
|
+
if (loading) return <div>Loading...</div>;
|
|
1660
|
+
|
|
1661
|
+
return (
|
|
1662
|
+
<ul>
|
|
1663
|
+
{users.map(u => (
|
|
1664
|
+
<li key={u.id}>{u.name}</li>
|
|
1665
|
+
))}
|
|
1666
|
+
</ul>
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
1669
|
+
```
|
|
1670
|
+
|
|
1671
|
+
**Key Points:**
|
|
1672
|
+
- ✅ **No repetitive error handling**: Errors already handled in request wrapper
|
|
1673
|
+
- ✅ **Race condition control**: Use `useRef` to manage `aborts` parameter
|
|
1674
|
+
- ✅ **Clean code**: Focus on business logic, not network error boilerplate
|
|
1675
|
+
- ✅ **Type safety**: Full TypeScript support with autocomplete and type checking
|
|
1676
|
+
|
|
1677
|
+
---
|
|
1678
|
+
|
|
1679
|
+
### Summary / 总结
|
|
1680
|
+
|
|
1681
|
+
**Architecture Benefits:**
|
|
1682
|
+
1. **Separation of Concerns**: Network layer (request.ts) vs Business layer (modules/) vs UI layer (components)
|
|
1683
|
+
2. **DRY Principle**: Error handling written once, used everywhere
|
|
1684
|
+
3. **Type Safety**: End-to-end type inference from API definition to component usage
|
|
1685
|
+
4. **Maintainability**: Domain-based modules make it easy to find and modify APIs
|
|
1686
|
+
5. **Scalability**: Easy to add new domains by creating new module files
|
|
1687
|
+
|
|
1688
|
+
**Core Philosophy:**
|
|
1689
|
+
- 🎯 **Centralize common logic** in request wrapper (errors, retries, caching)
|
|
1690
|
+
- 🎯 **Keep API definitions simple** with chainable type-safe methods
|
|
1691
|
+
- 🎯 **Components focus on UI** without repetitive error handling code
|
|
1692
|
+
- 🎯 **Handle edge cases** only when needed (race conditions, special business logic)
|