@nickyzj2023/utils 1.0.16 → 1.0.18

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.
Files changed (40) hide show
  1. package/README.md +35 -35
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +1 -1
  4. package/dist/is.d.ts +2 -1
  5. package/dist/object.d.ts +35 -0
  6. package/dist/string.d.ts +14 -0
  7. package/docs/assets/material-style.css +262 -0
  8. package/docs/assets/navigation.js +1 -1
  9. package/docs/assets/search.js +1 -1
  10. package/docs/functions/camelToSnake.html +178 -0
  11. package/docs/functions/fetcher.html +175 -2
  12. package/docs/functions/isObject.html +175 -2
  13. package/docs/functions/isPrimitive.html +176 -3
  14. package/docs/functions/mapKeys.html +180 -0
  15. package/docs/functions/mapValues.html +181 -0
  16. package/docs/functions/mergeObjects.html +175 -2
  17. package/docs/functions/sleep.html +175 -2
  18. package/docs/functions/snakeToCamel.html +178 -0
  19. package/docs/functions/timeLog.html +175 -2
  20. package/docs/functions/to.html +175 -2
  21. package/docs/functions/withCache.html +177 -4
  22. package/docs/hierarchy.html +174 -1
  23. package/docs/index.html +175 -2
  24. package/docs/modules.html +174 -1
  25. package/docs/types/DeepMapKeys.html +174 -0
  26. package/docs/types/DeepMapValues.html +174 -0
  27. package/docs/types/Primitive.html +174 -0
  28. package/docs/types/RequestInit.html +174 -1
  29. package/docs/types/SetTtl.html +174 -1
  30. package/package.json +6 -2
  31. package/src/dom.ts +10 -10
  32. package/src/hoc.ts +115 -115
  33. package/src/index.ts +1 -0
  34. package/src/is.ts +3 -1
  35. package/src/lru-cache.ts +50 -50
  36. package/src/network.ts +111 -111
  37. package/src/object.ts +113 -0
  38. package/src/string.ts +22 -0
  39. package/src/time.ts +11 -11
  40. package/tsconfig.json +32 -32
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
+ };
package/src/object.ts CHANGED
@@ -50,3 +50,116 @@ export const mergeObjects = <
50
50
 
51
51
  return result as T & U;
52
52
  };
53
+
54
+ // --- mapKeys ---
55
+
56
+ // 这里的 DeepMapKeys 只能承诺 key 是 string,无法推断出 key 的具体字面量变化
57
+ // 因为 TS 不支持根据任意函数反推 Key 的字面量类型
58
+ export type DeepMapKeys<T> =
59
+ T extends Array<infer U>
60
+ ? Array<DeepMapKeys<U>>
61
+ : T extends object
62
+ ? { [key: string]: DeepMapKeys<T[keyof T]> }
63
+ : T;
64
+
65
+ /**
66
+ * 递归处理对象里的 key
67
+ *
68
+ * @remarks
69
+ * 无法完整推导出类型,只能做到有递归,key 全为 string,value 为同层级的所有类型的联合
70
+ *
71
+ * @template T 要转换的对象
72
+ *
73
+ * @example
74
+ * const obj = { a: { b: 1 } };
75
+ * const result = mapKeys(obj, (key) => key.toUpperCase());
76
+ * console.log(result); // { A: { B: 1 } }
77
+ */
78
+ export const mapKeys = <T>(
79
+ obj: T,
80
+ getNewKey: (key: string) => string,
81
+ ): DeepMapKeys<T> => {
82
+ // 递归处理数组
83
+ if (Array.isArray(obj)) {
84
+ return obj.map((item) => mapKeys(item, getNewKey)) as any;
85
+ }
86
+
87
+ // 处理普通对象
88
+ if (isObject(obj)) {
89
+ const keys = Object.keys(obj);
90
+ return keys.reduce(
91
+ (result, key) => {
92
+ const newKey = getNewKey(key);
93
+ const value = (obj as any)[key];
94
+ result[newKey] = mapKeys(value, getNewKey);
95
+ return result;
96
+ },
97
+ {} as Record<string, any>,
98
+ ) as DeepMapKeys<T>;
99
+ }
100
+
101
+ // 处理非数组/对象
102
+ return obj as any;
103
+ };
104
+
105
+ // --- mapValues ---
106
+
107
+ // 这里的 DeepMapValues 尝试保留 key,但将 value 类型替换为 R
108
+ // 注意:如果原 value 是对象,我们递归处理结构,而不是把整个对象变成 R
109
+ export type DeepMapValues<T, R> =
110
+ T extends Array<infer U>
111
+ ? Array<DeepMapValues<U, R>>
112
+ : T extends object
113
+ ? { [K in keyof T]: T[K] extends object ? DeepMapValues<T[K], R> : R }
114
+ : R;
115
+
116
+ /**
117
+ * 递归处理对象里的 value
118
+ *
119
+ * @remarks
120
+ * 无法完整推导出类型,所有 value 最终都会变为 any
121
+ *
122
+ * @template T 要转换的对象
123
+ * @template R 转换后的值类型,为 any,无法进一步推导
124
+ *
125
+ * @example
126
+ * const obj = { a: 1, b: { c: 2 } };
127
+ * const result = mapValues(obj, (value, key) => isPrimitive(value) ? value + 1 : value);
128
+ * console.log(result); // { a: 2, b: { c: 3 } }
129
+ */
130
+ export const mapValues = <T, R = any>(
131
+ obj: T,
132
+ getNewValue: (value: any, key: string | number) => R,
133
+ ): DeepMapValues<T, R> => {
134
+ // 处理数组
135
+ if (Array.isArray(obj)) {
136
+ return obj.map((item, index) => {
137
+ // 如果元素是对象,则递归处理
138
+ if (isObject(item)) {
139
+ return mapValues(item, getNewValue);
140
+ }
141
+ // 如果元素是原始值,则直接应用 getNewValue(此时 key 为数组下标)
142
+ return getNewValue(item, index);
143
+ }) as any;
144
+ }
145
+
146
+ // 处理普通对象
147
+ if (isObject(obj)) {
148
+ const keys = Object.keys(obj);
149
+ return keys.reduce((result, key) => {
150
+ const value = (obj as any)[key];
151
+ // 如果值为对象或数组,则递归处理
152
+ if (!isPrimitive(value)) {
153
+ result[key] = mapValues(value, getNewValue);
154
+ }
155
+ // 否则直接应用 getNewValue
156
+ else {
157
+ result[key] = getNewValue(value, key);
158
+ }
159
+ return result;
160
+ }, {} as any) as DeepMapValues<T, R>;
161
+ }
162
+
163
+ // 处理非数组/对象
164
+ return obj as any;
165
+ };
package/src/string.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 转换下划线命名法为驼峰命名法
3
+ *
4
+ * @example
5
+ * snakeToCamel("user_name") // 'userName'
6
+ */
7
+ export const snakeToCamel = (str: string) => {
8
+ return str.replace(/_([a-zA-Z])/g, (match, pattern) => pattern.toUpperCase());
9
+ };
10
+
11
+ /**
12
+ * 转换驼峰命名法为下划线命名法
13
+ *
14
+ * @example
15
+ * camelToSnake("shouldComponentUpdate") // 'should_component_update'
16
+ */
17
+ export const camelToSnake = (str: string) => {
18
+ return str.replace(
19
+ /([A-Z])/g,
20
+ (match, pattern) => `_${pattern.toLowerCase()}`,
21
+ );
22
+ };
package/src/time.ts CHANGED
@@ -1,11 +1,11 @@
1
- /**
2
- * 延迟一段时间再执行后续代码
3
- * @param time 延迟时间,默认 150ms
4
- * @example
5
- * await sleep(1000); // 等待 1 秒执行后续代码
6
- */
7
- export const sleep = async (time = 150) => {
8
- return new Promise((resolve) => {
9
- setTimeout(resolve, time);
10
- });
11
- };
1
+ /**
2
+ * 延迟一段时间再执行后续代码
3
+ * @param time 延迟时间,默认 150ms
4
+ * @example
5
+ * await sleep(1000); // 等待 1 秒执行后续代码
6
+ */
7
+ export const sleep = async (time = 150) => {
8
+ return new Promise((resolve) => {
9
+ setTimeout(resolve, time);
10
+ });
11
+ };
package/tsconfig.json CHANGED
@@ -1,32 +1,32 @@
1
- {
2
- "compilerOptions": {
3
- // Environment setup & latest features
4
- "lib": ["ESNext", "DOM"],
5
- "target": "ESNext",
6
- "module": "Preserve",
7
- "moduleDetection": "force",
8
- "jsx": "react-jsx",
9
- "allowJs": true,
10
-
11
- // Bundler mode
12
- "moduleResolution": "bundler",
13
- "allowImportingTsExtensions": true,
14
- "verbatimModuleSyntax": true,
15
- "outDir": "dist",
16
- "declaration": true,
17
- "emitDeclarationOnly": true,
18
-
19
- // Best practices
20
- "strict": true,
21
- "skipLibCheck": true,
22
- "noFallthroughCasesInSwitch": true,
23
- "noUncheckedIndexedAccess": true,
24
- "noImplicitOverride": true,
25
-
26
- // Some stricter flags (disabled by default)
27
- "noUnusedLocals": false,
28
- "noUnusedParameters": false,
29
- "noPropertyAccessFromIndexSignature": false
30
- },
31
- "include": ["src"]
32
- }
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext", "DOM"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "outDir": "dist",
16
+ "declaration": true,
17
+ "emitDeclarationOnly": true,
18
+
19
+ // Best practices
20
+ "strict": true,
21
+ "skipLibCheck": true,
22
+ "noFallthroughCasesInSwitch": true,
23
+ "noUncheckedIndexedAccess": true,
24
+ "noImplicitOverride": true,
25
+
26
+ // Some stricter flags (disabled by default)
27
+ "noUnusedLocals": false,
28
+ "noUnusedParameters": false,
29
+ "noPropertyAccessFromIndexSignature": false
30
+ },
31
+ "include": ["src"]
32
+ }