@nickyzj2023/utils 1.0.18 → 1.0.19
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 +35 -35
- package/biome.json +40 -0
- package/dist/index.js +1 -1
- package/dist/string.d.ts +16 -2
- package/docs/assets/navigation.js +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/functions/camelToSnake.html +2 -2
- package/docs/functions/capitalize.html +178 -0
- package/docs/functions/decapitalize.html +178 -0
- package/docs/functions/fetcher.html +1 -1
- package/docs/functions/isObject.html +1 -1
- package/docs/functions/isPrimitive.html +1 -1
- package/docs/functions/mapKeys.html +1 -1
- package/docs/functions/mapValues.html +1 -1
- package/docs/functions/mergeObjects.html +1 -1
- package/docs/functions/sleep.html +1 -1
- package/docs/functions/snakeToCamel.html +2 -2
- package/docs/functions/timeLog.html +1 -1
- package/docs/functions/to.html +1 -1
- package/docs/functions/withCache.html +3 -3
- package/docs/modules.html +1 -1
- package/docs/types/DeepMapKeys.html +1 -1
- package/docs/types/DeepMapValues.html +1 -1
- package/docs/types/Primitive.html +1 -1
- package/docs/types/RequestInit.html +1 -1
- package/docs/types/SetTtl.html +1 -1
- package/package.json +2 -1
- package/src/dom.ts +10 -10
- package/src/hoc.ts +115 -115
- package/src/index.ts +7 -7
- package/src/is.ts +21 -21
- package/src/lru-cache.ts +50 -50
- package/src/network.ts +111 -111
- package/src/object.ts +165 -165
- package/src/string.ts +42 -22
- package/src/time.ts +11 -11
- package/tsconfig.json +32 -32
package/src/hoc.ts
CHANGED
|
@@ -1,115 +1,115 @@
|
|
|
1
|
-
type CacheEntry = {
|
|
2
|
-
value: any;
|
|
3
|
-
expiresAt: number; // 时间戳(毫秒)
|
|
4
|
-
};
|
|
5
|
-
|
|
6
|
-
export type SetTtl = (seconds: number) => void;
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* 创建一个带缓存的高阶函数
|
|
10
|
-
*
|
|
11
|
-
* @template Args 被包装函数的参数类型数组
|
|
12
|
-
* @template Result 被包装函数的返回类型
|
|
13
|
-
*
|
|
14
|
-
* @param fn 需要被缓存的函数,参数里附带的 setTtl 方法用于根据具体情况改写过期时间
|
|
15
|
-
* @param ttlSeconds 以秒为单位的过期时间,-1 表示永不过期,默认 -1,会被回调函数里的 setTtl() 覆盖
|
|
16
|
-
*
|
|
17
|
-
* @returns 返回包装后的函数,以及缓存相关的额外方法
|
|
18
|
-
*
|
|
19
|
-
* @example
|
|
20
|
-
* // 异步函数示例
|
|
21
|
-
* const fetchData = withCache(async function (url: string) {
|
|
22
|
-
* const data = await fetch(url).then((res) => res.json());
|
|
23
|
-
* this.setTtl(data.expiresIn); // 根据实际情况调整过期时间
|
|
24
|
-
* return data;
|
|
25
|
-
* });
|
|
26
|
-
*
|
|
27
|
-
* await fetchData(urlA);
|
|
28
|
-
* await fetchData(urlA); // 使用缓存结果
|
|
29
|
-
* await fetchData(urlB);
|
|
30
|
-
* await fetchData(urlB); // 使用缓存结果
|
|
31
|
-
*
|
|
32
|
-
* fetchData.clear(); // 清除缓存
|
|
33
|
-
* await fetchData(urlA); // 重新请求
|
|
34
|
-
* await fetchData(urlB); // 重新请求
|
|
35
|
-
*
|
|
36
|
-
* // 缓存过期前
|
|
37
|
-
* await sleep();
|
|
38
|
-
* fetchData.updateTtl(180); // 更新 ttl 并为所有未过期的缓存续期
|
|
39
|
-
* await fetchData(urlA); // 使用缓存结果
|
|
40
|
-
* await fetchData(urlB); // 使用缓存结果
|
|
41
|
-
*/
|
|
42
|
-
export const withCache = <Args extends any[], Result>(
|
|
43
|
-
fn: (this: { setTtl: SetTtl }, ...args: Args) => Result,
|
|
44
|
-
ttlSeconds = -1,
|
|
45
|
-
) => {
|
|
46
|
-
const cache = new Map<string, CacheEntry>();
|
|
47
|
-
|
|
48
|
-
const wrapped = (...args: Args): Result => {
|
|
49
|
-
const key = JSON.stringify(args);
|
|
50
|
-
const now = Date.now();
|
|
51
|
-
const entry = cache.get(key);
|
|
52
|
-
|
|
53
|
-
// 命中缓存且未过期
|
|
54
|
-
if (entry && now < entry.expiresAt) {
|
|
55
|
-
return entry.value;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
let expiresAt = ttlSeconds === -1 ? Infinity : now + ttlSeconds * 1000;
|
|
59
|
-
|
|
60
|
-
// 创建上下文,包含 setTtl 方法
|
|
61
|
-
const thisArg = {
|
|
62
|
-
setTtl: (ttl: number) => (expiresAt = now + ttl * 1000),
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const result = fn.apply(thisArg, args);
|
|
66
|
-
|
|
67
|
-
// 异步函数:缓存 Promise 的 resolved 值
|
|
68
|
-
if (result instanceof Promise) {
|
|
69
|
-
const promise = result.then((resolved) => {
|
|
70
|
-
cache.set(key, {
|
|
71
|
-
value: resolved,
|
|
72
|
-
expiresAt,
|
|
73
|
-
});
|
|
74
|
-
return resolved;
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
// 将 promise 先塞进去避免重复请求
|
|
78
|
-
cache.set(key, {
|
|
79
|
-
value: promise,
|
|
80
|
-
expiresAt,
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
return promise as Result;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// 同步函数缓存
|
|
87
|
-
cache.set(key, {
|
|
88
|
-
value: result,
|
|
89
|
-
expiresAt,
|
|
90
|
-
});
|
|
91
|
-
|
|
92
|
-
return result;
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
/** 手动清除缓存 */
|
|
96
|
-
wrapped.clear = () => cache.clear();
|
|
97
|
-
|
|
98
|
-
/** 更新 TTL,同时刷新所有未过期缓存的时间 */
|
|
99
|
-
wrapped.updateTtl = (seconds: number) => {
|
|
100
|
-
// 更新默认 TTL
|
|
101
|
-
ttlSeconds = seconds;
|
|
102
|
-
|
|
103
|
-
// 给未过期缓存续期
|
|
104
|
-
const now = Date.now();
|
|
105
|
-
const newExpiresAt = now + seconds * 1000;
|
|
106
|
-
for (const [key, entry] of cache.entries()) {
|
|
107
|
-
if (entry.expiresAt > now) {
|
|
108
|
-
entry.expiresAt = newExpiresAt;
|
|
109
|
-
cache.set(key, entry);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
return wrapped;
|
|
115
|
-
};
|
|
1
|
+
type CacheEntry = {
|
|
2
|
+
value: any;
|
|
3
|
+
expiresAt: number; // 时间戳(毫秒)
|
|
4
|
+
};
|
|
5
|
+
|
|
6
|
+
export type SetTtl = (seconds: number) => void;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 创建一个带缓存的高阶函数
|
|
10
|
+
*
|
|
11
|
+
* @template Args 被包装函数的参数类型数组
|
|
12
|
+
* @template Result 被包装函数的返回类型
|
|
13
|
+
*
|
|
14
|
+
* @param fn 需要被缓存的函数,参数里附带的 setTtl 方法用于根据具体情况改写过期时间
|
|
15
|
+
* @param ttlSeconds 以秒为单位的过期时间,-1 表示永不过期,默认 -1,会被回调函数里的 setTtl() 覆盖
|
|
16
|
+
*
|
|
17
|
+
* @returns 返回包装后的函数,以及缓存相关的额外方法
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* // 异步函数示例
|
|
21
|
+
* const fetchData = withCache(async function (url: string) {
|
|
22
|
+
* const data = await fetch(url).then((res) => res.json());
|
|
23
|
+
* this.setTtl(data.expiresIn); // 根据实际情况调整过期时间
|
|
24
|
+
* return data;
|
|
25
|
+
* });
|
|
26
|
+
*
|
|
27
|
+
* await fetchData(urlA);
|
|
28
|
+
* await fetchData(urlA); // 使用缓存结果
|
|
29
|
+
* await fetchData(urlB);
|
|
30
|
+
* await fetchData(urlB); // 使用缓存结果
|
|
31
|
+
*
|
|
32
|
+
* fetchData.clear(); // 清除缓存
|
|
33
|
+
* await fetchData(urlA); // 重新请求
|
|
34
|
+
* await fetchData(urlB); // 重新请求
|
|
35
|
+
*
|
|
36
|
+
* // 缓存过期前
|
|
37
|
+
* await sleep();
|
|
38
|
+
* fetchData.updateTtl(180); // 更新 ttl 并为所有未过期的缓存续期
|
|
39
|
+
* await fetchData(urlA); // 使用缓存结果
|
|
40
|
+
* await fetchData(urlB); // 使用缓存结果
|
|
41
|
+
*/
|
|
42
|
+
export const withCache = <Args extends any[], Result>(
|
|
43
|
+
fn: (this: { setTtl: SetTtl }, ...args: Args) => Result,
|
|
44
|
+
ttlSeconds = -1,
|
|
45
|
+
) => {
|
|
46
|
+
const cache = new Map<string, CacheEntry>();
|
|
47
|
+
|
|
48
|
+
const wrapped = (...args: Args): Result => {
|
|
49
|
+
const key = JSON.stringify(args);
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
const entry = cache.get(key);
|
|
52
|
+
|
|
53
|
+
// 命中缓存且未过期
|
|
54
|
+
if (entry && now < entry.expiresAt) {
|
|
55
|
+
return entry.value;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let expiresAt = ttlSeconds === -1 ? Infinity : now + ttlSeconds * 1000;
|
|
59
|
+
|
|
60
|
+
// 创建上下文,包含 setTtl 方法
|
|
61
|
+
const thisArg = {
|
|
62
|
+
setTtl: (ttl: number) => (expiresAt = now + ttl * 1000),
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const result = fn.apply(thisArg, args);
|
|
66
|
+
|
|
67
|
+
// 异步函数:缓存 Promise 的 resolved 值
|
|
68
|
+
if (result instanceof Promise) {
|
|
69
|
+
const promise = result.then((resolved) => {
|
|
70
|
+
cache.set(key, {
|
|
71
|
+
value: resolved,
|
|
72
|
+
expiresAt,
|
|
73
|
+
});
|
|
74
|
+
return resolved;
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// 将 promise 先塞进去避免重复请求
|
|
78
|
+
cache.set(key, {
|
|
79
|
+
value: promise,
|
|
80
|
+
expiresAt,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
return promise as Result;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 同步函数缓存
|
|
87
|
+
cache.set(key, {
|
|
88
|
+
value: result,
|
|
89
|
+
expiresAt,
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
return result;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** 手动清除缓存 */
|
|
96
|
+
wrapped.clear = () => cache.clear();
|
|
97
|
+
|
|
98
|
+
/** 更新 TTL,同时刷新所有未过期缓存的时间 */
|
|
99
|
+
wrapped.updateTtl = (seconds: number) => {
|
|
100
|
+
// 更新默认 TTL
|
|
101
|
+
ttlSeconds = seconds;
|
|
102
|
+
|
|
103
|
+
// 给未过期缓存续期
|
|
104
|
+
const now = Date.now();
|
|
105
|
+
const newExpiresAt = now + seconds * 1000;
|
|
106
|
+
for (const [key, entry] of cache.entries()) {
|
|
107
|
+
if (entry.expiresAt > now) {
|
|
108
|
+
entry.expiresAt = newExpiresAt;
|
|
109
|
+
cache.set(key, entry);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return wrapped;
|
|
115
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export * from "./dom";
|
|
2
|
-
export * from "./hoc";
|
|
3
|
-
export * from "./is";
|
|
4
|
-
export * from "./network";
|
|
5
|
-
export * from "./object";
|
|
6
|
-
export * from "./string";
|
|
7
|
-
export * from "./time";
|
|
1
|
+
export * from "./dom";
|
|
2
|
+
export * from "./hoc";
|
|
3
|
+
export * from "./is";
|
|
4
|
+
export * from "./network";
|
|
5
|
+
export * from "./object";
|
|
6
|
+
export * from "./string";
|
|
7
|
+
export * from "./time";
|
package/src/is.ts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
export type Primitive = number | string | boolean | symbol | bigint | undefined | null;
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 检测传入的值是否为**普通对象**
|
|
5
|
-
* @returns 如果是普通对象,返回 true,否则返回 false
|
|
6
|
-
*/
|
|
7
|
-
export const isObject = (value: any): value is object => {
|
|
8
|
-
return value?.constructor === Object;
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* 检测传入的值是否为**原始值**(number、string、boolean、symbol、bigint、undefined、null)
|
|
13
|
-
* @returns 如果是原始值,返回 true,否则返回 false
|
|
14
|
-
*/
|
|
15
|
-
export const isPrimitive = (value: any): value is Primitive => {
|
|
16
|
-
return (
|
|
17
|
-
value === null ||
|
|
18
|
-
value === undefined ||
|
|
19
|
-
(typeof value !== "object" && typeof value !== "function")
|
|
20
|
-
);
|
|
21
|
-
};
|
|
1
|
+
export type Primitive = number | string | boolean | symbol | bigint | undefined | null;
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 检测传入的值是否为**普通对象**
|
|
5
|
+
* @returns 如果是普通对象,返回 true,否则返回 false
|
|
6
|
+
*/
|
|
7
|
+
export const isObject = (value: any): value is object => {
|
|
8
|
+
return value?.constructor === Object;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 检测传入的值是否为**原始值**(number、string、boolean、symbol、bigint、undefined、null)
|
|
13
|
+
* @returns 如果是原始值,返回 true,否则返回 false
|
|
14
|
+
*/
|
|
15
|
+
export const isPrimitive = (value: any): value is Primitive => {
|
|
16
|
+
return (
|
|
17
|
+
value === null ||
|
|
18
|
+
value === undefined ||
|
|
19
|
+
(typeof value !== "object" && typeof value !== "function")
|
|
20
|
+
);
|
|
21
|
+
};
|
package/src/lru-cache.ts
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 简易 LRU 缓存
|
|
3
|
-
* @example
|
|
4
|
-
* const cache = new LRUCache<string, number>(2);
|
|
5
|
-
* cache.set("a", 1);
|
|
6
|
-
* cache.set("b", 2);
|
|
7
|
-
* cache.set("c", 3); // 缓存已满,a 被淘汰
|
|
8
|
-
* cache.get("a"); // undefined
|
|
9
|
-
*/
|
|
10
|
-
class LRUCache<K, V> {
|
|
11
|
-
private cache: Map<K, V>;
|
|
12
|
-
private maxSize: number;
|
|
13
|
-
|
|
14
|
-
constructor(maxSize = 10) {
|
|
15
|
-
this.cache = new Map();
|
|
16
|
-
this.maxSize = maxSize;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
get(key: K): V | undefined {
|
|
20
|
-
const value = this.cache.get(key);
|
|
21
|
-
if (!value) {
|
|
22
|
-
return undefined;
|
|
23
|
-
}
|
|
24
|
-
// 重置缓存顺序
|
|
25
|
-
this.cache.delete(key);
|
|
26
|
-
this.cache.set(key, value);
|
|
27
|
-
return value;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
set(key: K, value: V) {
|
|
31
|
-
// 刷新缓存
|
|
32
|
-
if (this.cache.has(key)) {
|
|
33
|
-
this.cache.delete(key);
|
|
34
|
-
}
|
|
35
|
-
// 删除最旧的缓存
|
|
36
|
-
else if (this.cache.size >= this.maxSize) {
|
|
37
|
-
const oldestKey = [...this.cache.keys()][0];
|
|
38
|
-
if (oldestKey) {
|
|
39
|
-
this.cache.delete(oldestKey);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
this.cache.set(key, value);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
has(key: K) {
|
|
46
|
-
return this.cache.has(key);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export default LRUCache;
|
|
1
|
+
/**
|
|
2
|
+
* 简易 LRU 缓存
|
|
3
|
+
* @example
|
|
4
|
+
* const cache = new LRUCache<string, number>(2);
|
|
5
|
+
* cache.set("a", 1);
|
|
6
|
+
* cache.set("b", 2);
|
|
7
|
+
* cache.set("c", 3); // 缓存已满,a 被淘汰
|
|
8
|
+
* cache.get("a"); // undefined
|
|
9
|
+
*/
|
|
10
|
+
class LRUCache<K, V> {
|
|
11
|
+
private cache: Map<K, V>;
|
|
12
|
+
private maxSize: number;
|
|
13
|
+
|
|
14
|
+
constructor(maxSize = 10) {
|
|
15
|
+
this.cache = new Map();
|
|
16
|
+
this.maxSize = maxSize;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get(key: K): V | undefined {
|
|
20
|
+
const value = this.cache.get(key);
|
|
21
|
+
if (!value) {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
// 重置缓存顺序
|
|
25
|
+
this.cache.delete(key);
|
|
26
|
+
this.cache.set(key, value);
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
set(key: K, value: V) {
|
|
31
|
+
// 刷新缓存
|
|
32
|
+
if (this.cache.has(key)) {
|
|
33
|
+
this.cache.delete(key);
|
|
34
|
+
}
|
|
35
|
+
// 删除最旧的缓存
|
|
36
|
+
else if (this.cache.size >= this.maxSize) {
|
|
37
|
+
const oldestKey = [...this.cache.keys()][0];
|
|
38
|
+
if (oldestKey) {
|
|
39
|
+
this.cache.delete(oldestKey);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
this.cache.set(key, value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
has(key: K) {
|
|
46
|
+
return this.cache.has(key);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export default LRUCache;
|
package/src/network.ts
CHANGED
|
@@ -1,111 +1,111 @@
|
|
|
1
|
-
import { isObject } from "./is";
|
|
2
|
-
import { mergeObjects } from "./object";
|
|
3
|
-
|
|
4
|
-
export type RequestInit = BunFetchRequestInit & {
|
|
5
|
-
parser?: (response: Response) => Promise<any>;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* 基于 Fetch API 的请求客户端
|
|
10
|
-
* @param baseURL 接口前缀,如 https://nickyzj.run:3030,也可以不填
|
|
11
|
-
* @param defaultOptions 客户端级别的请求选项,方法级别的选项会覆盖这里的相同值
|
|
12
|
-
*
|
|
13
|
-
* @remarks
|
|
14
|
-
* 特性:
|
|
15
|
-
* - 合并客户端级别、方法级别的请求选项
|
|
16
|
-
* - 在 body 里直接传递对象
|
|
17
|
-
* - 可选择使用 to() 处理返回结果为 [Error, Response]
|
|
18
|
-
* - 可选择使用 withCache() 缓存请求结果
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* // 用法1:创建客户端
|
|
22
|
-
* const api = fetcher("https://nickyzj.run:3030", { headers: { Authorization: "Bearer token" } });
|
|
23
|
-
* const res = await api.get<Blog>("/blogs/hello-world");
|
|
24
|
-
*
|
|
25
|
-
* // 用法2:直接发送请求
|
|
26
|
-
* const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world");
|
|
27
|
-
*
|
|
28
|
-
* // 安全处理返回结果
|
|
29
|
-
* const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
|
|
30
|
-
* if (error) {
|
|
31
|
-
* console.error(error);
|
|
32
|
-
* return;
|
|
33
|
-
* }
|
|
34
|
-
*
|
|
35
|
-
* // 缓存请求结果
|
|
36
|
-
* const getBlogs = withCache(api.get);
|
|
37
|
-
* await getBlogs("/blogs");
|
|
38
|
-
* await sleep(1000);
|
|
39
|
-
* await getBlogs("/blogs"); // 不请求,使用缓存结果
|
|
40
|
-
*/
|
|
41
|
-
export const fetcher = (baseURL = "", defaultOptions: RequestInit = {}) => {
|
|
42
|
-
const createRequest = async <T>(
|
|
43
|
-
path: string,
|
|
44
|
-
requestOptions: RequestInit = {},
|
|
45
|
-
) => {
|
|
46
|
-
// 构建完整 URL
|
|
47
|
-
const url = baseURL ? `${baseURL}${path}` : path;
|
|
48
|
-
|
|
49
|
-
// 合并 options
|
|
50
|
-
const { parser, ...options } = mergeObjects(defaultOptions, requestOptions);
|
|
51
|
-
|
|
52
|
-
// 转换 body 为字符串
|
|
53
|
-
if (isObject(options.body)) {
|
|
54
|
-
options.body = JSON.stringify(options.body);
|
|
55
|
-
options.headers = {
|
|
56
|
-
...options.headers,
|
|
57
|
-
"Content-Type": "application/json",
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// 发送请求
|
|
62
|
-
const response = await fetch(url, options);
|
|
63
|
-
if (!response.ok) {
|
|
64
|
-
throw new Error(response.statusText);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const data = await (parser?.(response) ?? response.json());
|
|
68
|
-
return data as T;
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
return {
|
|
72
|
-
get: <T>(url: string, options: Omit<RequestInit, "method"> = {}) =>
|
|
73
|
-
createRequest<T>(url, { ...options, method: "GET" }),
|
|
74
|
-
|
|
75
|
-
post: <T>(
|
|
76
|
-
url: string,
|
|
77
|
-
body: any,
|
|
78
|
-
options: Omit<RequestInit, "method" | "body"> = {},
|
|
79
|
-
) => createRequest<T>(url, { ...options, method: "POST", body }),
|
|
80
|
-
|
|
81
|
-
put: <T>(
|
|
82
|
-
url: string,
|
|
83
|
-
body: any,
|
|
84
|
-
options: Omit<RequestInit, "method" | "body"> = {},
|
|
85
|
-
) => createRequest<T>(url, { ...options, method: "PUT", body }),
|
|
86
|
-
|
|
87
|
-
delete: <T>(
|
|
88
|
-
url: string,
|
|
89
|
-
options: Omit<RequestInit, "method" | "body"> = {},
|
|
90
|
-
) => createRequest<T>(url, { ...options, method: "DELETE" }),
|
|
91
|
-
};
|
|
92
|
-
};
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Go 语言风格的异步处理方式
|
|
96
|
-
* @param promise 一个能被 await 的异步函数
|
|
97
|
-
* @returns 如果成功,返回 [null, 异步函数结果],否则返回 [Error, undefined]
|
|
98
|
-
*
|
|
99
|
-
* @example
|
|
100
|
-
* const [error, response] = await to(fetcher().get<Blog>("/blogs/hello-world"));
|
|
101
|
-
*/
|
|
102
|
-
export const to = async <T, U = Error>(
|
|
103
|
-
promise: Promise<T>,
|
|
104
|
-
): Promise<[null, T] | [U, undefined]> => {
|
|
105
|
-
try {
|
|
106
|
-
const response = await promise;
|
|
107
|
-
return [null, response];
|
|
108
|
-
} catch (error) {
|
|
109
|
-
return [error as U, undefined];
|
|
110
|
-
}
|
|
111
|
-
};
|
|
1
|
+
import { isObject } from "./is";
|
|
2
|
+
import { mergeObjects } from "./object";
|
|
3
|
+
|
|
4
|
+
export type RequestInit = BunFetchRequestInit & {
|
|
5
|
+
parser?: (response: Response) => Promise<any>;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 基于 Fetch API 的请求客户端
|
|
10
|
+
* @param baseURL 接口前缀,如 https://nickyzj.run:3030,也可以不填
|
|
11
|
+
* @param defaultOptions 客户端级别的请求选项,方法级别的选项会覆盖这里的相同值
|
|
12
|
+
*
|
|
13
|
+
* @remarks
|
|
14
|
+
* 特性:
|
|
15
|
+
* - 合并客户端级别、方法级别的请求选项
|
|
16
|
+
* - 在 body 里直接传递对象
|
|
17
|
+
* - 可选择使用 to() 处理返回结果为 [Error, Response]
|
|
18
|
+
* - 可选择使用 withCache() 缓存请求结果
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* // 用法1:创建客户端
|
|
22
|
+
* const api = fetcher("https://nickyzj.run:3030", { headers: { Authorization: "Bearer token" } });
|
|
23
|
+
* const res = await api.get<Blog>("/blogs/hello-world");
|
|
24
|
+
*
|
|
25
|
+
* // 用法2:直接发送请求
|
|
26
|
+
* const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world");
|
|
27
|
+
*
|
|
28
|
+
* // 安全处理返回结果
|
|
29
|
+
* const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
|
|
30
|
+
* if (error) {
|
|
31
|
+
* console.error(error);
|
|
32
|
+
* return;
|
|
33
|
+
* }
|
|
34
|
+
*
|
|
35
|
+
* // 缓存请求结果
|
|
36
|
+
* const getBlogs = withCache(api.get);
|
|
37
|
+
* await getBlogs("/blogs");
|
|
38
|
+
* await sleep(1000);
|
|
39
|
+
* await getBlogs("/blogs"); // 不请求,使用缓存结果
|
|
40
|
+
*/
|
|
41
|
+
export const fetcher = (baseURL = "", defaultOptions: RequestInit = {}) => {
|
|
42
|
+
const createRequest = async <T>(
|
|
43
|
+
path: string,
|
|
44
|
+
requestOptions: RequestInit = {},
|
|
45
|
+
) => {
|
|
46
|
+
// 构建完整 URL
|
|
47
|
+
const url = baseURL ? `${baseURL}${path}` : path;
|
|
48
|
+
|
|
49
|
+
// 合并 options
|
|
50
|
+
const { parser, ...options } = mergeObjects(defaultOptions, requestOptions);
|
|
51
|
+
|
|
52
|
+
// 转换 body 为字符串
|
|
53
|
+
if (isObject(options.body)) {
|
|
54
|
+
options.body = JSON.stringify(options.body);
|
|
55
|
+
options.headers = {
|
|
56
|
+
...options.headers,
|
|
57
|
+
"Content-Type": "application/json",
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 发送请求
|
|
62
|
+
const response = await fetch(url, options);
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
throw new Error(response.statusText);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const data = await (parser?.(response) ?? response.json());
|
|
68
|
+
return data as T;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
get: <T>(url: string, options: Omit<RequestInit, "method"> = {}) =>
|
|
73
|
+
createRequest<T>(url, { ...options, method: "GET" }),
|
|
74
|
+
|
|
75
|
+
post: <T>(
|
|
76
|
+
url: string,
|
|
77
|
+
body: any,
|
|
78
|
+
options: Omit<RequestInit, "method" | "body"> = {},
|
|
79
|
+
) => createRequest<T>(url, { ...options, method: "POST", body }),
|
|
80
|
+
|
|
81
|
+
put: <T>(
|
|
82
|
+
url: string,
|
|
83
|
+
body: any,
|
|
84
|
+
options: Omit<RequestInit, "method" | "body"> = {},
|
|
85
|
+
) => createRequest<T>(url, { ...options, method: "PUT", body }),
|
|
86
|
+
|
|
87
|
+
delete: <T>(
|
|
88
|
+
url: string,
|
|
89
|
+
options: Omit<RequestInit, "method" | "body"> = {},
|
|
90
|
+
) => createRequest<T>(url, { ...options, method: "DELETE" }),
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Go 语言风格的异步处理方式
|
|
96
|
+
* @param promise 一个能被 await 的异步函数
|
|
97
|
+
* @returns 如果成功,返回 [null, 异步函数结果],否则返回 [Error, undefined]
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* const [error, response] = await to(fetcher().get<Blog>("/blogs/hello-world"));
|
|
101
|
+
*/
|
|
102
|
+
export const to = async <T, U = Error>(
|
|
103
|
+
promise: Promise<T>,
|
|
104
|
+
): Promise<[null, T] | [U, undefined]> => {
|
|
105
|
+
try {
|
|
106
|
+
const response = await promise;
|
|
107
|
+
return [null, response];
|
|
108
|
+
} catch (error) {
|
|
109
|
+
return [error as U, undefined];
|
|
110
|
+
}
|
|
111
|
+
};
|