@taicode/common-web 1.1.0 → 1.1.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.
Files changed (50) hide show
  1. package/output/cache-api/cache-api.d.ts +13 -0
  2. package/output/cache-api/cache-api.d.ts.map +1 -0
  3. package/output/cache-api/cache-api.js +114 -0
  4. package/output/cache-api/cache-api.test.d.ts +2 -0
  5. package/output/cache-api/cache-api.test.d.ts.map +1 -0
  6. package/output/cache-api/cache-api.test.js +348 -0
  7. package/output/cache-api/index.d.ts +2 -0
  8. package/output/cache-api/index.d.ts.map +1 -0
  9. package/output/cache-api/index.js +1 -0
  10. package/output/helpers/cache-api/cache-api.d.ts +13 -0
  11. package/output/helpers/cache-api/cache-api.d.ts.map +1 -0
  12. package/output/helpers/cache-api/cache-api.js +114 -0
  13. package/output/helpers/cache-api/cache-api.test.d.ts +2 -0
  14. package/output/helpers/cache-api/cache-api.test.d.ts.map +1 -0
  15. package/output/helpers/cache-api/cache-api.test.js +348 -0
  16. package/output/helpers/cache-api/index.d.ts +2 -0
  17. package/output/helpers/cache-api/index.d.ts.map +1 -0
  18. package/output/helpers/cache-api/index.js +1 -0
  19. package/output/helpers/side-cache/side-cache.d.ts +5 -2
  20. package/output/helpers/side-cache/side-cache.d.ts.map +1 -1
  21. package/output/helpers/side-cache/side-cache.js +41 -10
  22. package/output/helpers/side-cache/side-cache.test.js +166 -76
  23. package/output/service/index.d.ts +2 -0
  24. package/output/service/index.d.ts.map +1 -0
  25. package/output/service/index.js +1 -0
  26. package/output/service/service.d.ts +114 -0
  27. package/output/service/service.d.ts.map +1 -0
  28. package/output/service/service.js +189 -0
  29. package/output/service/service.test.d.ts +2 -0
  30. package/output/service/service.test.d.ts.map +1 -0
  31. package/output/service/service.test.jsx +367 -0
  32. package/output/side-cache/index.d.ts +2 -0
  33. package/output/side-cache/index.d.ts.map +1 -0
  34. package/output/side-cache/index.js +1 -0
  35. package/output/side-cache/side-cache.d.ts +10 -0
  36. package/output/side-cache/side-cache.d.ts.map +1 -0
  37. package/output/side-cache/side-cache.js +137 -0
  38. package/output/side-cache/side-cache.test.d.ts +2 -0
  39. package/output/side-cache/side-cache.test.d.ts.map +1 -0
  40. package/output/side-cache/side-cache.test.js +179 -0
  41. package/output/use-observer/index.d.ts +2 -0
  42. package/output/use-observer/index.d.ts.map +1 -0
  43. package/output/use-observer/index.js +1 -0
  44. package/output/use-observer/use-observer.d.ts +3 -0
  45. package/output/use-observer/use-observer.d.ts.map +1 -0
  46. package/output/use-observer/use-observer.js +16 -0
  47. package/output/use-observer/use-observer.test.d.ts +2 -0
  48. package/output/use-observer/use-observer.test.d.ts.map +1 -0
  49. package/output/use-observer/use-observer.test.jsx +134 -0
  50. package/package.json +2 -1
@@ -0,0 +1,348 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { runInAction, configure } from 'mobx';
3
+ import { CacheApi } from './cache-api';
4
+ // 配置 MobX 在测试环境中的行为
5
+ configure({
6
+ enforceActions: 'never',
7
+ computedRequiresReaction: false,
8
+ reactionRequiresObservable: false,
9
+ observableRequiresReaction: false,
10
+ disableErrorBoundaries: true
11
+ });
12
+ describe('CacheApi', () => {
13
+ let mockApiFunc;
14
+ let cacheApi;
15
+ beforeEach(() => {
16
+ mockApiFunc = vi.fn();
17
+ cacheApi = new CacheApi(mockApiFunc);
18
+ });
19
+ afterEach(() => {
20
+ vi.clearAllMocks();
21
+ });
22
+ describe('构造函数', () => {
23
+ it('应该正确初始化 CacheApi 实例', () => {
24
+ expect(cacheApi).toBeInstanceOf(CacheApi);
25
+ expect(cacheApi.value).toBeUndefined();
26
+ });
27
+ it('应该正确绑定 send 方法', () => {
28
+ const { send } = cacheApi;
29
+ expect(typeof send).toBe('function');
30
+ });
31
+ });
32
+ describe('value getter', () => {
33
+ it('初始状态下应该返回 undefined', () => {
34
+ expect(cacheApi.value).toBeUndefined();
35
+ });
36
+ it('应该在成功调用后返回缓存的值', async () => {
37
+ const expectedResult = 'test-result';
38
+ mockApiFunc.mockResolvedValue(expectedResult);
39
+ await cacheApi.send('param1', 123);
40
+ expect(cacheApi.value).toBe(expectedResult);
41
+ });
42
+ it('应该在多次调用后返回最新的缓存值', async () => {
43
+ const result1 = 'result-1';
44
+ const result2 = 'result-2';
45
+ mockApiFunc.mockResolvedValueOnce(result1);
46
+ await cacheApi.send('param1', 123);
47
+ expect(cacheApi.value).toBe(result1);
48
+ mockApiFunc.mockResolvedValueOnce(result2);
49
+ await cacheApi.send('param2', 456);
50
+ expect(cacheApi.value).toBe(result2);
51
+ });
52
+ });
53
+ describe('empty getter', () => {
54
+ it('初始状态下应该返回 true', () => {
55
+ expect(cacheApi.empty).toBe(true);
56
+ });
57
+ it('成功调用后应该返回 false', async () => {
58
+ mockApiFunc.mockResolvedValue('test-result');
59
+ await cacheApi.send('param1', 123);
60
+ expect(cacheApi.empty).toBe(false);
61
+ });
62
+ it('即使调用失败也应该保持 true', async () => {
63
+ const error = new Error('API Error');
64
+ mockApiFunc.mockRejectedValue(error);
65
+ try {
66
+ await cacheApi.send('param1', 123);
67
+ }
68
+ catch (e) {
69
+ // 忽略错误
70
+ }
71
+ expect(cacheApi.empty).toBe(true);
72
+ });
73
+ it('empty 应该是一个 computed 属性', () => {
74
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(cacheApi), 'empty');
75
+ expect(descriptor).toBeDefined();
76
+ expect(descriptor === null || descriptor === void 0 ? void 0 : descriptor.get).toBeDefined();
77
+ expect(descriptor === null || descriptor === void 0 ? void 0 : descriptor.set).toBeUndefined();
78
+ });
79
+ });
80
+ describe('send 方法', () => {
81
+ it('应该调用传入的 API 函数', async () => {
82
+ const expectedResult = 'api-result';
83
+ mockApiFunc.mockResolvedValue(expectedResult);
84
+ const result = await cacheApi.send('test', 42);
85
+ expect(mockApiFunc).toHaveBeenCalledTimes(1);
86
+ expect(mockApiFunc).toHaveBeenCalledWith('test', 42);
87
+ expect(result).toBe(expectedResult);
88
+ });
89
+ it('应该正确传递多个参数', async () => {
90
+ const params = ['hello', 999];
91
+ mockApiFunc.mockResolvedValue('success');
92
+ await cacheApi.send(...params);
93
+ expect(mockApiFunc).toHaveBeenCalledWith(...params);
94
+ });
95
+ it('应该返回 API 函数的结果', async () => {
96
+ const expectedResult = { data: 'test', status: 'ok' };
97
+ mockApiFunc.mockResolvedValue(expectedResult);
98
+ const result = await cacheApi.send('param', 1);
99
+ expect(result).toEqual(expectedResult);
100
+ });
101
+ it('应该处理 API 函数抛出的异常', async () => {
102
+ const error = new Error('API Error');
103
+ mockApiFunc.mockRejectedValue(error);
104
+ await expect(cacheApi.send('param', 1)).rejects.toThrow('API Error');
105
+ });
106
+ });
107
+ describe('缓存功能', () => {
108
+ it('相同参数应该使用缓存', async () => {
109
+ const result = 'cached-result';
110
+ mockApiFunc.mockResolvedValue(result);
111
+ // 第一次调用
112
+ const firstResult = await cacheApi.send('same', 123);
113
+ expect(firstResult).toBe(result);
114
+ expect(cacheApi.value).toBe(result);
115
+ // 第二次调用相同参数,应该从缓存返回
116
+ const secondResult = await cacheApi.send('same', 123);
117
+ expect(secondResult).toBe(result);
118
+ expect(cacheApi.value).toBe(result);
119
+ // API 函数应该被调用两次(SideCache 的 handle 方法会每次都调用)
120
+ expect(mockApiFunc).toHaveBeenCalledTimes(2);
121
+ });
122
+ it('不同参数应该触发新的 API 调用', async () => {
123
+ mockApiFunc.mockResolvedValueOnce('result1');
124
+ mockApiFunc.mockResolvedValueOnce('result2');
125
+ await cacheApi.send('param1', 1);
126
+ await cacheApi.send('param2', 2);
127
+ expect(mockApiFunc).toHaveBeenCalledTimes(2);
128
+ expect(mockApiFunc).toHaveBeenNthCalledWith(1, 'param1', 1);
129
+ expect(mockApiFunc).toHaveBeenNthCalledWith(2, 'param2', 2);
130
+ });
131
+ it('应该正确更新当前缓存的 key', async () => {
132
+ mockApiFunc.mockResolvedValueOnce('value1');
133
+ mockApiFunc.mockResolvedValueOnce('value2');
134
+ await cacheApi.send('key1', 1);
135
+ expect(cacheApi.value).toBe('value1');
136
+ await cacheApi.send('key2', 2);
137
+ expect(cacheApi.value).toBe('value2');
138
+ });
139
+ });
140
+ describe('异步操作', () => {
141
+ it('应该正确处理并发调用', async () => {
142
+ let resolveCount = 0;
143
+ mockApiFunc.mockImplementation(async (param) => {
144
+ await new Promise(resolve => setTimeout(resolve, 10));
145
+ return `result-${param}-${++resolveCount}`;
146
+ });
147
+ const [result1, result2, result3] = await Promise.all([
148
+ cacheApi.send('param1', 1),
149
+ cacheApi.send('param2', 2),
150
+ cacheApi.send('param3', 3)
151
+ ]);
152
+ expect(result1).toMatch(/result-param1-\d/);
153
+ expect(result2).toMatch(/result-param2-\d/);
154
+ expect(result3).toMatch(/result-param3-\d/);
155
+ expect(mockApiFunc).toHaveBeenCalledTimes(3);
156
+ });
157
+ it('应该在异步操作完成后更新 value', async () => {
158
+ const delay = 50;
159
+ mockApiFunc.mockImplementation(async () => {
160
+ await new Promise(resolve => setTimeout(resolve, delay));
161
+ return 'delayed-result';
162
+ });
163
+ // 开始异步操作,此时 value 应该还是之前的值
164
+ const promise = cacheApi.send('test', 1);
165
+ // 等待一小段时间,但还没完成
166
+ await new Promise(resolve => setTimeout(resolve, delay / 2));
167
+ // 完成异步操作
168
+ const result = await promise;
169
+ expect(result).toBe('delayed-result');
170
+ expect(cacheApi.value).toBe('delayed-result');
171
+ });
172
+ });
173
+ describe('边缘情况', () => {
174
+ it('应该处理 null 返回值', async () => {
175
+ mockApiFunc.mockResolvedValue(null);
176
+ const result = await cacheApi.send('test', 1);
177
+ expect(result).toBeNull();
178
+ expect(cacheApi.value).toBeNull();
179
+ });
180
+ it('应该处理 undefined 返回值', async () => {
181
+ mockApiFunc.mockResolvedValue(undefined);
182
+ const result = await cacheApi.send('test', 1);
183
+ expect(result).toBeUndefined();
184
+ expect(cacheApi.value).toBeUndefined();
185
+ });
186
+ it('应该处理复杂对象参数', async () => {
187
+ const complexParam = { nested: { value: 'test' }, array: [1, 2, 3] };
188
+ const complexMockFunc = vi.fn();
189
+ complexMockFunc.mockResolvedValue('complex-result');
190
+ // 创建一个接受复杂参数的 CacheApi
191
+ const complexCacheApi = new CacheApi(complexMockFunc);
192
+ const result = await complexCacheApi.send(complexParam);
193
+ expect(result).toBe('complex-result');
194
+ expect(complexMockFunc).toHaveBeenCalledWith(complexParam);
195
+ });
196
+ it('should handle no parameters', async () => {
197
+ const noParamApi = new CacheApi(() => Promise.resolve('no-param-result'));
198
+ const result = await noParamApi.send();
199
+ expect(result).toBe('no-param-result');
200
+ });
201
+ });
202
+ describe('MobX 集成', () => {
203
+ it('value 应该是一个 computed 属性', () => {
204
+ // 通过检查属性描述符来验证这是一个 computed 属性
205
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(cacheApi), 'value');
206
+ expect(descriptor).toBeDefined();
207
+ expect(descriptor === null || descriptor === void 0 ? void 0 : descriptor.get).toBeDefined();
208
+ expect(descriptor === null || descriptor === void 0 ? void 0 : descriptor.set).toBeUndefined();
209
+ });
210
+ it('value 变化应该触发 MobX 反应', async () => {
211
+ let reactionCount = 0;
212
+ let lastValue = undefined;
213
+ // 创建一个简单的反应来监听 value 变化
214
+ const disposer = runInAction(() => {
215
+ const reaction = () => {
216
+ reactionCount++;
217
+ lastValue = cacheApi.value;
218
+ };
219
+ // 初始调用
220
+ reaction();
221
+ return reaction;
222
+ });
223
+ mockApiFunc.mockResolvedValue('new-value');
224
+ await cacheApi.send('test', 1);
225
+ // 清理
226
+ if (typeof disposer === 'function') {
227
+ disposer();
228
+ }
229
+ expect(lastValue).toBe('new-value');
230
+ });
231
+ });
232
+ describe('类型安全', () => {
233
+ it('应该保持参数类型安全', () => {
234
+ // 这个测试主要是在编译时进行类型检查
235
+ // 如果类型不匹配,TypeScript 编译器会报错
236
+ const typedApi = new CacheApi((str, num, bool) => {
237
+ return Promise.resolve({ result: `${str}-${num}-${bool}` });
238
+ });
239
+ // 正确的调用
240
+ expect(() => typedApi.send('test', 42, true)).not.toThrow();
241
+ // 以下调用在 TypeScript 中会产生编译错误(在运行时测试中跳过)
242
+ // typedApi.send('test', 'wrong-type', true) // 第二个参数应该是 number
243
+ // typedApi.send('test', 42) // 缺少第三个参数
244
+ });
245
+ });
246
+ describe('loading 状态', () => {
247
+ it('初始状态下 loading 应该为 false', () => {
248
+ expect(cacheApi.loading).toBe(false);
249
+ });
250
+ it('发送请求时 loading 应该为 true', async () => {
251
+ let resolveFn;
252
+ const promise = new Promise((resolve) => {
253
+ resolveFn = resolve;
254
+ });
255
+ mockApiFunc.mockReturnValue(promise);
256
+ // 开始请求
257
+ const sendPromise = cacheApi.send('test', 1);
258
+ // 此时应该是 loading 状态
259
+ expect(cacheApi.loading).toBe(true);
260
+ // 完成请求
261
+ resolveFn('result');
262
+ await sendPromise;
263
+ // 请求完成后 loading 应该为 false
264
+ expect(cacheApi.loading).toBe(false);
265
+ });
266
+ it('请求失败后 loading 应该为 false', async () => {
267
+ const error = new Error('API Error');
268
+ mockApiFunc.mockRejectedValue(error);
269
+ try {
270
+ await cacheApi.send('test', 1);
271
+ }
272
+ catch (e) {
273
+ // 忽略错误
274
+ }
275
+ expect(cacheApi.loading).toBe(false);
276
+ });
277
+ it('并发请求时 loading 状态应该正确处理', async () => {
278
+ const resolvers = [];
279
+ mockApiFunc.mockImplementation((param) => {
280
+ return new Promise((resolve) => {
281
+ resolvers.push((value) => resolve(`${param}-${value}`));
282
+ });
283
+ });
284
+ // 启动三个并发请求
285
+ const promise1 = cacheApi.send('req1', 1);
286
+ const promise2 = cacheApi.send('req2', 2);
287
+ const promise3 = cacheApi.send('req3', 3);
288
+ // 此时应该有三个请求正在进行,loading 为 true
289
+ expect(cacheApi.loading).toBe(true);
290
+ // 完成第一个请求
291
+ resolvers[0]('result1');
292
+ await promise1;
293
+ // 还有两个请求在进行,loading 仍为 true
294
+ expect(cacheApi.loading).toBe(true);
295
+ // 完成第二个请求
296
+ resolvers[1]('result2');
297
+ await promise2;
298
+ // 还有一个请求在进行,loading 仍为 true
299
+ expect(cacheApi.loading).toBe(true);
300
+ // 完成第三个请求
301
+ resolvers[2]('result3');
302
+ await promise3;
303
+ // 所有请求完成,loading 为 false
304
+ expect(cacheApi.loading).toBe(false);
305
+ });
306
+ it('部分并发请求失败时 loading 状态应该正确', async () => {
307
+ let resolveSuccess;
308
+ let rejectError;
309
+ mockApiFunc.mockImplementation((param) => {
310
+ if (param === 'success') {
311
+ return new Promise((resolve) => {
312
+ resolveSuccess = resolve;
313
+ });
314
+ }
315
+ else {
316
+ return new Promise((_, reject) => {
317
+ rejectError = reject;
318
+ });
319
+ }
320
+ });
321
+ // 启动两个请求,一个成功一个失败
322
+ const successPromise = cacheApi.send('success', 1);
323
+ const errorPromise = cacheApi.send('error', 2);
324
+ expect(cacheApi.loading).toBe(true);
325
+ // 先让失败的请求完成
326
+ rejectError(new Error('Failed'));
327
+ try {
328
+ await errorPromise;
329
+ }
330
+ catch (e) {
331
+ // 忽略错误
332
+ }
333
+ // 还有一个成功的请求在进行,loading 仍为 true
334
+ expect(cacheApi.loading).toBe(true);
335
+ // 完成成功的请求
336
+ resolveSuccess('success-result');
337
+ await successPromise;
338
+ // 所有请求完成,loading 为 false
339
+ expect(cacheApi.loading).toBe(false);
340
+ });
341
+ it('loading 应该是一个 computed 属性', () => {
342
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(cacheApi), 'loading');
343
+ expect(descriptor).toBeDefined();
344
+ expect(descriptor === null || descriptor === void 0 ? void 0 : descriptor.get).toBeDefined();
345
+ expect(descriptor === null || descriptor === void 0 ? void 0 : descriptor.set).toBeUndefined();
346
+ });
347
+ });
348
+ });
@@ -0,0 +1,2 @@
1
+ export { CacheApi } from './cache-api';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../source/helpers/cache-api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA"}
@@ -0,0 +1 @@
1
+ export { CacheApi } from './cache-api';
@@ -1,7 +1,10 @@
1
1
  export declare class SideCache<T> {
2
+ private accessor emptyFlag;
2
3
  private accessor currentKey;
3
4
  private accessor cache;
4
- get value(): T | null;
5
- handle<F extends ((...args: unknown[]) => Promise<T | null>)>(key: unknown, func: F): Promise<T | null>;
5
+ get value(): T | undefined;
6
+ get empty(): boolean;
7
+ handle<F extends ((...args: unknown[]) => T)>(key: unknown, func: F): T;
8
+ handle<F extends ((...args: unknown[]) => Promise<T> | T)>(key: unknown, func: F): Promise<T> | T;
6
9
  }
7
10
  //# sourceMappingURL=side-cache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"side-cache.d.ts","sourceRoot":"","sources":["../../../source/helpers/side-cache/side-cache.ts"],"names":[],"mappings":"AAOA,qBAAa,SAAS,CAAC,CAAC;IAEtB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAsB;IAGjD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoC;IAE1D,IACW,KAAK,IAAI,CAAC,GAAG,IAAI,CAG3B;IAGY,MAAM,CAAC,CAAC,SAAS,CAAC,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;CAiBrH"}
1
+ {"version":3,"file":"side-cache.d.ts","sourceRoot":"","sources":["../../../source/helpers/side-cache/side-cache.ts"],"names":[],"mappings":"AAWA,qBAAa,SAAS,CAAC,CAAC;IAEtB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAgB;IAG1C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAoB;IAG/C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoC;IAE1D,IACW,KAAK,IAAI,CAAC,GAAG,SAAS,CAIhC;IAED,IACW,KAAK,IAAI,OAAO,CAE1B;IAED,MAAM,CAAC,CAAC,SAAS,CAAC,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC;IACvE,MAAM,CAAC,CAAC,SAAS,CAAC,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;CAuClG"}
@@ -44,10 +44,16 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
44
44
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
45
45
  };
46
46
  import { action, computed, observable, runInAction } from 'mobx';
47
+ function isPromiseLike(value) {
48
+ return value != null && typeof value.then === 'function';
49
+ }
47
50
  let SideCache = (() => {
48
- var _a, _SideCache_currentKey_accessor_storage, _SideCache_cache_accessor_storage;
51
+ var _a, _SideCache_emptyFlag_accessor_storage, _SideCache_currentKey_accessor_storage, _SideCache_cache_accessor_storage;
49
52
  var _b, _c;
50
53
  let _instanceExtraInitializers = [];
54
+ let _emptyFlag_decorators;
55
+ let _emptyFlag_initializers = [];
56
+ let _emptyFlag_extraInitializers = [];
51
57
  let _currentKey_decorators;
52
58
  let _currentKey_initializers = [];
53
59
  let _currentKey_extraInitializers = [];
@@ -55,25 +61,44 @@ let SideCache = (() => {
55
61
  let _cache_initializers = [];
56
62
  let _cache_extraInitializers = [];
57
63
  let _get_value_decorators;
64
+ let _get_empty_decorators;
58
65
  let _handle_decorators;
59
66
  return _a = class SideCache {
67
+ get emptyFlag() { return __classPrivateFieldGet(this, _SideCache_emptyFlag_accessor_storage, "f"); }
68
+ set emptyFlag(value) { __classPrivateFieldSet(this, _SideCache_emptyFlag_accessor_storage, value, "f"); }
60
69
  get currentKey() { return __classPrivateFieldGet(this, _SideCache_currentKey_accessor_storage, "f"); }
61
70
  set currentKey(value) { __classPrivateFieldSet(this, _SideCache_currentKey_accessor_storage, value, "f"); }
62
71
  get cache() { return __classPrivateFieldGet(this, _SideCache_cache_accessor_storage, "f"); }
63
72
  set cache(value) { __classPrivateFieldSet(this, _SideCache_cache_accessor_storage, value, "f"); }
64
73
  get value() {
65
- var _b;
66
74
  if (this.currentKey == null)
67
- return null;
68
- return ((_b = this.cache[this.currentKey]) === null || _b === void 0 ? void 0 : _b.data) || null;
75
+ return undefined;
76
+ const cacheItem = this.cache[this.currentKey];
77
+ return cacheItem ? cacheItem.data : undefined;
78
+ }
79
+ get empty() {
80
+ return this.emptyFlag;
69
81
  }
70
- async handle(key, func) {
71
- const keyStringify = JSON.stringify(key); // 不需要跨设备、软件一致,所以直接用 JSON.stringify
82
+ handle(key, func) {
83
+ var _b;
84
+ // 不需要跨设备、软件一致,所以直接用 JSON.stringify
85
+ // 但需要处理 JSON.stringify(undefined) 返回 undefined 的情况
86
+ const keyStringify = (_b = JSON.stringify(key)) !== null && _b !== void 0 ? _b : 'undefined';
87
+ // 这会让外面立马可以拿到之前缓存的值,如果存在的话
72
88
  runInAction(() => this.currentKey = keyStringify);
73
- const funcReturn = await func();
74
- if (funcReturn == null)
75
- return funcReturn;
89
+ const funcReturn = func();
90
+ if (isPromiseLike(funcReturn)) {
91
+ return funcReturn.then(result => runInAction(() => {
92
+ this.emptyFlag = false;
93
+ this.cache = Object.assign(Object.assign({}, this.cache), { [keyStringify]: {
94
+ data: result,
95
+ createTime: new Date().toISOString()
96
+ } });
97
+ return result;
98
+ }));
99
+ }
76
100
  runInAction(() => {
101
+ this.emptyFlag = false;
77
102
  this.cache = Object.assign(Object.assign({}, this.cache), { [keyStringify]: {
78
103
  data: funcReturn,
79
104
  createTime: new Date().toISOString()
@@ -82,22 +107,28 @@ let SideCache = (() => {
82
107
  return funcReturn;
83
108
  }
84
109
  constructor() {
85
- _SideCache_currentKey_accessor_storage.set(this, (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _currentKey_initializers, null)));
110
+ _SideCache_emptyFlag_accessor_storage.set(this, (__runInitializers(this, _instanceExtraInitializers), __runInitializers(this, _emptyFlag_initializers, true)));
111
+ _SideCache_currentKey_accessor_storage.set(this, (__runInitializers(this, _emptyFlag_extraInitializers), __runInitializers(this, _currentKey_initializers, void 0)));
86
112
  _SideCache_cache_accessor_storage.set(this, (__runInitializers(this, _currentKey_extraInitializers), __runInitializers(this, _cache_initializers, {})));
87
113
  __runInitializers(this, _cache_extraInitializers);
88
114
  }
89
115
  },
116
+ _SideCache_emptyFlag_accessor_storage = new WeakMap(),
90
117
  _SideCache_currentKey_accessor_storage = new WeakMap(),
91
118
  _SideCache_cache_accessor_storage = new WeakMap(),
92
119
  (() => {
93
120
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
121
+ _emptyFlag_decorators = [observable];
94
122
  _currentKey_decorators = [observable];
95
123
  _cache_decorators = [(_b = observable).ref.bind(_b)];
96
124
  _get_value_decorators = [computed];
125
+ _get_empty_decorators = [computed];
97
126
  _handle_decorators = [(_c = action).bound.bind(_c)];
127
+ __esDecorate(_a, null, _emptyFlag_decorators, { kind: "accessor", name: "emptyFlag", static: false, private: false, access: { has: obj => "emptyFlag" in obj, get: obj => obj.emptyFlag, set: (obj, value) => { obj.emptyFlag = value; } }, metadata: _metadata }, _emptyFlag_initializers, _emptyFlag_extraInitializers);
98
128
  __esDecorate(_a, null, _currentKey_decorators, { kind: "accessor", name: "currentKey", static: false, private: false, access: { has: obj => "currentKey" in obj, get: obj => obj.currentKey, set: (obj, value) => { obj.currentKey = value; } }, metadata: _metadata }, _currentKey_initializers, _currentKey_extraInitializers);
99
129
  __esDecorate(_a, null, _cache_decorators, { kind: "accessor", name: "cache", static: false, private: false, access: { has: obj => "cache" in obj, get: obj => obj.cache, set: (obj, value) => { obj.cache = value; } }, metadata: _metadata }, _cache_initializers, _cache_extraInitializers);
100
130
  __esDecorate(_a, null, _get_value_decorators, { kind: "getter", name: "value", static: false, private: false, access: { has: obj => "value" in obj, get: obj => obj.value }, metadata: _metadata }, null, _instanceExtraInitializers);
131
+ __esDecorate(_a, null, _get_empty_decorators, { kind: "getter", name: "empty", static: false, private: false, access: { has: obj => "empty" in obj, get: obj => obj.empty }, metadata: _metadata }, null, _instanceExtraInitializers);
101
132
  __esDecorate(_a, null, _handle_decorators, { kind: "method", name: "handle", static: false, private: false, access: { has: obj => "handle" in obj, get: obj => obj.handle }, metadata: _metadata }, null, _instanceExtraInitializers);
102
133
  if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
103
134
  })(),