@hyper-fetch/core 9.6.1 → 9.7.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.
Files changed (134) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -0,0 +1,667 @@
1
+ import type { CacheAsyncStorageType, CacheValueType } from "cache";
2
+ import { Cache } from "cache";
3
+ import { Client } from "client";
4
+ import { LoggerManager } from "managers";
5
+ import { scopeKey } from "request";
6
+
7
+ import {
8
+ createCacheErrorResponse,
9
+ createCacheResponse,
10
+ createCacheValue,
11
+ createDeferred,
12
+ createLazyStorage,
13
+ flushPromises,
14
+ getUnhandledRejections,
15
+ } from "../../utils/fixtures.utils";
16
+
17
+ const cacheKey = "lazy-key";
18
+ const version = "test-version";
19
+
20
+ const createLazyClient = (source = new Map<string, CacheValueType>()) => {
21
+ const lazy = createLazyStorage(source);
22
+ const client = new Client({
23
+ url: "shared-base-url",
24
+ cache: () => new Cache({ lazyStorage: lazy.storage, version }),
25
+ });
26
+ const request = client.createRequest<{ response: any }>()({ endpoint: "/users", cacheKey });
27
+
28
+ return { client, request, ...lazy };
29
+ };
30
+
31
+ const createFailingClient = (lazyStorage: CacheAsyncStorageType) => {
32
+ const logger = vi.fn();
33
+ const client = new Client({ url: "shared-base-url", cache: () => new Cache({ lazyStorage, version }) })
34
+ .setDebug(true)
35
+ .setLogger(() => new LoggerManager({ logger }));
36
+ const request = client.createRequest<{ response: any }>()({ endpoint: "/users", cacheKey });
37
+
38
+ return { client, request, logger };
39
+ };
40
+
41
+ describe("Cache [ Lazy Storage Resilience ]", () => {
42
+ beforeEach(() => {
43
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
44
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
45
+ });
46
+
47
+ afterEach(() => {
48
+ vi.clearAllTimers();
49
+ vi.useRealTimers();
50
+ });
51
+
52
+ describe("When the data is loaded from the lazy storage", () => {
53
+ it("should return nothing right away and emit the data once it is loaded", async () => {
54
+ const { client, source } = createLazyClient();
55
+ const value = createCacheValue({ cacheKey, version, data: { id: 1 } });
56
+ const spy = vi.fn();
57
+ source.set(cacheKey, value);
58
+ client.cache.events.onDataByKey(cacheKey, spy);
59
+
60
+ expect(client.cache.get(cacheKey)).toBeUndefined();
61
+ await flushPromises();
62
+
63
+ expect(spy).toHaveBeenCalledTimes(1);
64
+ expect(spy.mock.calls[0][0]).toStrictEqual({ ...value, cached: true });
65
+ expect(client.cache.get(cacheKey)).toStrictEqual(value);
66
+ });
67
+
68
+ it("should resolve the lazy resource with the loaded data", async () => {
69
+ const { client, source } = createLazyClient();
70
+ const value = createCacheValue({ cacheKey, version, data: { id: 1 } });
71
+ source.set(cacheKey, value);
72
+
73
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toStrictEqual(value);
74
+ });
75
+
76
+ it("should resolve with nothing when no storage holds the data", async () => {
77
+ const { client } = createLazyClient();
78
+ const spy = vi.fn();
79
+ client.cache.events.onData(spy);
80
+
81
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
82
+ expect(spy).not.toHaveBeenCalled();
83
+ });
84
+
85
+ it("should resolve with the sync data when there is no lazy storage", async () => {
86
+ const client = new Client({ url: "shared-base-url" });
87
+ const request = client.createRequest<{ response: any }>()({ endpoint: "/users", cacheKey });
88
+ client.cache.set(request, createCacheResponse({ id: 1 }));
89
+
90
+ const resource = await client.cache.getLazyResource(cacheKey);
91
+
92
+ expect(resource?.data).toStrictEqual({ id: 1 });
93
+ });
94
+
95
+ it("should collect the loaded data when its cache time passes", async () => {
96
+ const { client, source } = createLazyClient();
97
+ source.set(
98
+ cacheKey,
99
+ createCacheValue({ cacheKey, version, cacheTime: 1000, responseTimestamp: Date.now() - 400 }),
100
+ );
101
+ await client.cache.getLazyResource(cacheKey);
102
+
103
+ vi.advanceTimersByTime(599);
104
+ expect(client.cache.storage.get(cacheKey)).toBeDefined();
105
+
106
+ vi.advanceTimersByTime(1);
107
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
108
+ expect(source.has(cacheKey)).toBeFalse();
109
+ });
110
+
111
+ it("should emit the scoped data with the cache key of the request", async () => {
112
+ const { client, source, request } = createLazyClient();
113
+ const scoped = request.setScope("user-1");
114
+ const storageKey = scopeKey(scoped.cacheKey, "user-1");
115
+ const spy = vi.fn();
116
+ source.set(storageKey, createCacheValue({ cacheKey: scoped.cacheKey, scope: "user-1", version, data: "scoped" }));
117
+ client.cache.events.onDataByKey(scoped.cacheKey, spy);
118
+
119
+ await client.cache.getLazyResource(storageKey);
120
+
121
+ expect(spy).toHaveBeenCalledTimes(1);
122
+ expect(scoped.read()?.data).toBe("scoped");
123
+ });
124
+ });
125
+
126
+ describe("When the lazy data gets stale", () => {
127
+ const staleTime = 5000;
128
+
129
+ it("should load the data just before the stale time passes", async () => {
130
+ const { client, source } = createLazyClient();
131
+ source.set(
132
+ cacheKey,
133
+ createCacheValue({ cacheKey, version, staleTime, responseTimestamp: Date.now() - staleTime + 1 }),
134
+ );
135
+
136
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeDefined();
137
+ expect(client.cache.storage.get(cacheKey)).toBeDefined();
138
+ });
139
+
140
+ it("should not load the data exactly when the stale time passes", async () => {
141
+ const { client, source } = createLazyClient();
142
+ const spy = vi.fn();
143
+ source.set(
144
+ cacheKey,
145
+ createCacheValue({ cacheKey, version, staleTime, responseTimestamp: Date.now() - staleTime }),
146
+ );
147
+ client.cache.events.onData(spy);
148
+
149
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
150
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
151
+ expect(spy).not.toHaveBeenCalled();
152
+ });
153
+
154
+ it("should not load the data after the stale time passed", async () => {
155
+ const { client, source } = createLazyClient();
156
+ source.set(
157
+ cacheKey,
158
+ createCacheValue({ cacheKey, version, staleTime, responseTimestamp: Date.now() - staleTime - 1 }),
159
+ );
160
+
161
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
162
+ });
163
+
164
+ it("should keep the stale data in the lazy storage until its cache time passes", async () => {
165
+ const { client, source } = createLazyClient();
166
+ source.set(
167
+ cacheKey,
168
+ createCacheValue({
169
+ cacheKey,
170
+ version,
171
+ staleTime,
172
+ cacheTime: 60_000,
173
+ responseTimestamp: Date.now() - staleTime,
174
+ }),
175
+ );
176
+
177
+ await client.cache.getLazyResource(cacheKey);
178
+
179
+ expect(source.has(cacheKey)).toBeTrue();
180
+ });
181
+
182
+ it.each([
183
+ { name: "infinite", value: Infinity },
184
+ { name: "serialized to null", value: null as unknown as number },
185
+ ])("should load the data with the $name stale time", async ({ value }) => {
186
+ const { client, source } = createLazyClient();
187
+ source.set(
188
+ cacheKey,
189
+ createCacheValue({ cacheKey, version, staleTime: value, cacheTime: Infinity, responseTimestamp: 1 }),
190
+ );
191
+
192
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeDefined();
193
+ expect(client.cache.storage.get(cacheKey)).toBeDefined();
194
+ });
195
+ });
196
+
197
+ describe("When the lazy data is outdated", () => {
198
+ it("should remove the data older than its cache time from the lazy storage", async () => {
199
+ const { client, source, spies } = createLazyClient();
200
+ const spy = vi.fn();
201
+ source.set(
202
+ cacheKey,
203
+ createCacheValue({
204
+ cacheKey,
205
+ version,
206
+ staleTime: 60_000,
207
+ cacheTime: 1000,
208
+ responseTimestamp: Date.now() - 1001,
209
+ }),
210
+ );
211
+ client.cache.events.onData(spy);
212
+
213
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
214
+
215
+ expect(spies.delete).toHaveBeenCalledWith(cacheKey);
216
+ expect(source.has(cacheKey)).toBeFalse();
217
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
218
+ expect(spy).not.toHaveBeenCalled();
219
+ });
220
+
221
+ it("should keep the data as old as its cache time", async () => {
222
+ const { client, source } = createLazyClient();
223
+ source.set(
224
+ cacheKey,
225
+ createCacheValue({
226
+ cacheKey,
227
+ version,
228
+ staleTime: 60_000,
229
+ cacheTime: 1000,
230
+ responseTimestamp: Date.now() - 1000,
231
+ }),
232
+ );
233
+
234
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeDefined();
235
+ expect(source.has(cacheKey)).toBeTrue();
236
+ });
237
+
238
+ it("should keep the outdated data in the lazy storage while offline", async () => {
239
+ const { client, source } = createLazyClient();
240
+ source.set(
241
+ cacheKey,
242
+ createCacheValue({ cacheKey, version, staleTime: 500, cacheTime: 1000, responseTimestamp: Date.now() - 5000 }),
243
+ );
244
+ client.appManager.setOnline(false);
245
+
246
+ await client.cache.getLazyResource(cacheKey);
247
+
248
+ expect(source.has(cacheKey)).toBeTrue();
249
+ });
250
+
251
+ it.each([
252
+ { name: "infinite", value: Infinity },
253
+ { name: "serialized to null", value: null as unknown as number },
254
+ ])("should never remove the data with the $name cache time", async ({ value }) => {
255
+ const { client, source } = createLazyClient();
256
+ source.set(
257
+ cacheKey,
258
+ createCacheValue({ cacheKey, version, staleTime: 500, cacheTime: value, responseTimestamp: 1 }),
259
+ );
260
+
261
+ await client.cache.getLazyResource(cacheKey);
262
+
263
+ expect(source.has(cacheKey)).toBeTrue();
264
+ });
265
+ });
266
+
267
+ describe("When both storages hold the data", () => {
268
+ it("should keep the sync data when it is newer", async () => {
269
+ const { client, source, request } = createLazyClient();
270
+ const spy = vi.fn();
271
+ source.set(cacheKey, createCacheValue({ cacheKey, version, data: "lazy", responseTimestamp: Date.now() - 100 }));
272
+ client.cache.storage.set(cacheKey, createCacheValue({ cacheKey, version, data: "sync" }));
273
+ client.cache.events.onData(spy);
274
+
275
+ const resource = await client.cache.getLazyResource(cacheKey);
276
+
277
+ expect(resource?.data).toBe("sync");
278
+ expect(request.read()?.data).toBe("sync");
279
+ expect(spy).not.toHaveBeenCalled();
280
+ });
281
+
282
+ it("should keep the sync data when both are equally old", async () => {
283
+ const { client, source, request } = createLazyClient();
284
+ source.set(cacheKey, createCacheValue({ cacheKey, version, data: "lazy" }));
285
+ client.cache.storage.set(cacheKey, createCacheValue({ cacheKey, version, data: "sync" }));
286
+
287
+ await client.cache.getLazyResource(cacheKey);
288
+
289
+ expect(request.read()?.data).toBe("sync");
290
+ });
291
+
292
+ it("should replace the sync data when the lazy data is newer", async () => {
293
+ const { client, source, request } = createLazyClient();
294
+ const spy = vi.fn();
295
+ source.set(cacheKey, createCacheValue({ cacheKey, version, data: "lazy" }));
296
+ client.cache.storage.set(
297
+ cacheKey,
298
+ createCacheValue({ cacheKey, version, data: "sync", responseTimestamp: Date.now() - 100 }),
299
+ );
300
+ client.cache.events.onDataByKey(cacheKey, spy);
301
+
302
+ await client.cache.getLazyResource(cacheKey);
303
+
304
+ expect(request.read()?.data).toBe("lazy");
305
+ expect(spy).toHaveBeenCalledTimes(1);
306
+ });
307
+
308
+ it("should end up with the newest data when the lazy reads resolve out of order", async () => {
309
+ const older = createDeferred<CacheValueType>();
310
+ const newer = createDeferred<CacheValueType>();
311
+ const get = vi.fn().mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
312
+ const { client, request } = createFailingClient({
313
+ get,
314
+ set: async () => {},
315
+ delete: async () => {},
316
+ keys: async () => [],
317
+ });
318
+
319
+ const firstRead = client.cache.getLazyResource(cacheKey);
320
+ const secondRead = client.cache.getLazyResource(cacheKey);
321
+
322
+ newer.resolve(createCacheValue({ cacheKey, version, data: "newer" }));
323
+ await secondRead;
324
+ older.resolve(createCacheValue({ cacheKey, version, data: "older", responseTimestamp: Date.now() - 100 }));
325
+ await firstRead;
326
+
327
+ expect(request.read()?.data).toBe("newer");
328
+ });
329
+
330
+ it("should not override the response which arrived while the lazy storage was read", async () => {
331
+ const lazyRead = createDeferred<CacheValueType>();
332
+ const { client, request } = createFailingClient({
333
+ get: () => lazyRead.promise as Promise<any>,
334
+ set: async () => {},
335
+ delete: async () => {},
336
+ keys: async () => [],
337
+ });
338
+ const persisted = createCacheValue({ cacheKey, version, data: "persisted", responseTimestamp: Date.now() - 100 });
339
+
340
+ const pendingRead = client.cache.getLazyResource(cacheKey);
341
+ client.cache.set(request, createCacheResponse("fresh"));
342
+ lazyRead.resolve(persisted);
343
+ await pendingRead;
344
+
345
+ expect(request.read()?.data).toBe("fresh");
346
+ });
347
+ });
348
+
349
+ describe("When the version does not match", () => {
350
+ it("should remove the lazy data saved by another version", async () => {
351
+ const { client, source, spies } = createLazyClient();
352
+ const spy = vi.fn();
353
+ source.set(cacheKey, createCacheValue({ cacheKey, version: "previous-version" }));
354
+ client.cache.events.onData(spy);
355
+
356
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
357
+
358
+ expect(spies.delete).toHaveBeenCalledTimes(1);
359
+ expect(source.has(cacheKey)).toBeFalse();
360
+ expect(spy).not.toHaveBeenCalled();
361
+ });
362
+
363
+ it("should never return the sync data saved by another version", async () => {
364
+ const { client } = createLazyClient();
365
+ client.cache.storage.set(cacheKey, createCacheValue({ cacheKey, version: "previous-version" }));
366
+
367
+ expect(client.cache.get(cacheKey)).toBeUndefined();
368
+ await flushPromises();
369
+
370
+ expect(client.cache.get(cacheKey)).toBeUndefined();
371
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
372
+ });
373
+
374
+ it("should notify the listeners about the removed sync data only once", async () => {
375
+ const { client } = createLazyClient();
376
+ const spy = vi.fn();
377
+ client.cache.storage.set(cacheKey, createCacheValue({ cacheKey, version: "previous-version" }));
378
+ client.cache.events.onDelete(spy);
379
+
380
+ client.cache.get(cacheKey);
381
+ client.cache.get(cacheKey);
382
+ await flushPromises();
383
+
384
+ expect(spy).toHaveBeenCalledTimes(1);
385
+ });
386
+
387
+ it("should not resolve the lazy resource with the sync data saved by another version", async () => {
388
+ const { client } = createLazyClient();
389
+ client.cache.storage.set(cacheKey, createCacheValue({ cacheKey, version: "previous-version" }));
390
+
391
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
392
+ });
393
+
394
+ it("should use the default version when none is provided", () => {
395
+ expect(new Cache().version).toBe("0.0.1");
396
+ expect(new Cache({ version: "2.0.0" }).version).toBe("2.0.0");
397
+ });
398
+ });
399
+
400
+ describe("When the data is written", () => {
401
+ it("should save the stored response in the lazy storage", () => {
402
+ const { client, request, source } = createLazyClient();
403
+
404
+ client.cache.set(request, createCacheResponse({ id: 1 }));
405
+
406
+ expect(source.get(cacheKey)).toBe(client.cache.storage.get(cacheKey));
407
+ });
408
+
409
+ it("should save the scoped response under the storage key", () => {
410
+ const { client, request, source } = createLazyClient();
411
+ const scoped = request.setScope("user-1");
412
+
413
+ client.cache.set(scoped, createCacheResponse({ id: 1 }));
414
+
415
+ expect([...source.keys()]).toStrictEqual([scopeKey(cacheKey, "user-1")]);
416
+ });
417
+
418
+ it("should not save the responses which are not stored", () => {
419
+ const { client, request, spies } = createLazyClient();
420
+
421
+ client.cache.set(request.setCache(false), createCacheResponse({ id: 1 }));
422
+ client.cache.set(request, createCacheErrorResponse(new Error("Failed")));
423
+
424
+ expect(spies.set).not.toHaveBeenCalled();
425
+ });
426
+
427
+ it("should save the updated element in the lazy storage", () => {
428
+ const { client, request, source } = createLazyClient();
429
+ client.cache.set(request, createCacheResponse({ id: 1 }));
430
+
431
+ client.cache.update(request, { data: { id: 2 } });
432
+
433
+ expect(source.get(cacheKey)?.data).toStrictEqual({ id: 2 });
434
+ });
435
+
436
+ it("should remove the deleted element from the lazy storage", () => {
437
+ const { client, request, source } = createLazyClient();
438
+ client.cache.set(request, createCacheResponse({ id: 1 }));
439
+
440
+ client.cache.delete(cacheKey);
441
+
442
+ expect(source.has(cacheKey)).toBeFalse();
443
+ });
444
+
445
+ it("should remove the collected element from the lazy storage", () => {
446
+ const { client, request, source } = createLazyClient();
447
+ client.cache.set(request.setCacheTime(1000), createCacheResponse({ id: 1 }));
448
+
449
+ vi.advanceTimersByTime(1000);
450
+
451
+ expect(source.has(cacheKey)).toBeFalse();
452
+ });
453
+
454
+ it("should not read the lazy storage when the data is set", () => {
455
+ const { client, request, spies } = createLazyClient();
456
+
457
+ client.cache.set(request, createCacheResponse({ id: 1 }));
458
+
459
+ expect(spies.get).not.toHaveBeenCalled();
460
+ });
461
+ });
462
+
463
+ describe("When listing the keys", () => {
464
+ it("should return the lazy keys without the duplicates", async () => {
465
+ const { client } = createFailingClient({
466
+ ...createLazyStorage().storage,
467
+ keys: async () => ["first", "second", "first"],
468
+ });
469
+
470
+ await expect(client.cache.getLazyKeys()).resolves.toStrictEqual(["first", "second"]);
471
+ });
472
+
473
+ it("should accept the iterator of the lazy keys", async () => {
474
+ const { client, source } = createLazyClient();
475
+ source.set("first", createCacheValue());
476
+ const iteratorClient = createFailingClient({
477
+ ...createLazyStorage().storage,
478
+ keys: async () => source.keys(),
479
+ }).client;
480
+
481
+ await expect(iteratorClient.cache.getLazyKeys()).resolves.toStrictEqual(["first"]);
482
+ await expect(client.cache.getLazyKeys()).resolves.toStrictEqual(["first"]);
483
+ });
484
+
485
+ it("should merge the keys of both storages without the duplicates", async () => {
486
+ const { client, request, source } = createLazyClient();
487
+ source.set("only-lazy", createCacheValue({ cacheKey: "only-lazy", version }));
488
+ client.cache.set(request, createCacheResponse({ id: 1 }));
489
+ client.cache.storage.set("only-sync", createCacheValue({ cacheKey: "only-sync", version }));
490
+
491
+ const keys = await client.cache.getAllKeys();
492
+
493
+ expect(keys).toIncludeSameMembers([cacheKey, "only-lazy", "only-sync"]);
494
+ });
495
+
496
+ it("should return only the sync keys from the keys method", () => {
497
+ const { client, request, source } = createLazyClient();
498
+ source.set("only-lazy", createCacheValue({ cacheKey: "only-lazy", version }));
499
+ client.cache.set(request, createCacheResponse({ id: 1 }));
500
+
501
+ expect(client.cache.keys()).toStrictEqual([cacheKey]);
502
+ });
503
+
504
+ it("should pass the failure of the lazy keys to the caller", async () => {
505
+ const { client } = createFailingClient({
506
+ ...createLazyStorage().storage,
507
+ keys: async () => {
508
+ throw new Error("Keys failed");
509
+ },
510
+ });
511
+
512
+ await expect(client.cache.getLazyKeys()).rejects.toThrow("Keys failed");
513
+ await expect(client.cache.getAllKeys()).rejects.toThrow("Keys failed");
514
+ });
515
+ });
516
+
517
+ describe("When the lazy storage fails", () => {
518
+ const rejectingStorage = (): CacheAsyncStorageType => ({
519
+ get: () => Promise.reject(new Error("Get failed")),
520
+ set: () => Promise.reject(new Error("Set failed")),
521
+ delete: () => Promise.reject(new Error("Delete failed")),
522
+ keys: () => Promise.reject(new Error("Keys failed")),
523
+ });
524
+
525
+ const throwingStorage = (): CacheAsyncStorageType => ({
526
+ get: () => {
527
+ throw new Error("Get failed");
528
+ },
529
+ set: () => {
530
+ throw new Error("Set failed");
531
+ },
532
+ delete: () => {
533
+ throw new Error("Delete failed");
534
+ },
535
+ keys: () => {
536
+ throw new Error("Keys failed");
537
+ },
538
+ });
539
+
540
+ it.each([
541
+ { name: "rejects", createStorage: rejectingStorage },
542
+ { name: "throws", createStorage: throwingStorage },
543
+ ])("should store and emit the response when the lazy write $name", async ({ createStorage }) => {
544
+ const { client, request } = createFailingClient(createStorage());
545
+ const spy = vi.fn();
546
+ client.cache.events.onDataByKey(cacheKey, spy);
547
+
548
+ const rejections = await getUnhandledRejections(() => {
549
+ client.cache.set(request, createCacheResponse({ id: 1 }));
550
+ });
551
+
552
+ expect(rejections).toHaveLength(0);
553
+ expect(client.cache.storage.get(cacheKey)?.data).toStrictEqual({ id: 1 });
554
+ expect(spy).toHaveBeenCalledTimes(1);
555
+ expect(client.cache.garbageCollectors.size).toBe(1);
556
+ });
557
+
558
+ it.each([
559
+ { name: "rejects", createStorage: rejectingStorage },
560
+ { name: "throws", createStorage: throwingStorage },
561
+ ])("should return the sync data when the lazy read $name", async ({ createStorage }) => {
562
+ const { client, request } = createFailingClient(createStorage());
563
+ client.cache.set(request, createCacheResponse({ id: 1 }));
564
+
565
+ let read: CacheValueType | undefined;
566
+ const rejections = await getUnhandledRejections(() => {
567
+ read = client.cache.get(cacheKey);
568
+ });
569
+
570
+ expect(rejections).toHaveLength(0);
571
+ expect(read?.data).toStrictEqual({ id: 1 });
572
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toStrictEqual(read);
573
+ });
574
+
575
+ it.each([
576
+ { name: "rejects", createStorage: rejectingStorage },
577
+ { name: "throws", createStorage: throwingStorage },
578
+ ])("should delete the element and notify the listeners when the lazy delete $name", async ({ createStorage }) => {
579
+ const { client, request } = createFailingClient(createStorage());
580
+ const spy = vi.fn();
581
+ client.cache.set(request, createCacheResponse({ id: 1 }));
582
+ client.cache.events.onDeleteByKey(cacheKey, spy);
583
+
584
+ const rejections = await getUnhandledRejections(() => {
585
+ client.cache.delete(cacheKey);
586
+ });
587
+
588
+ expect(rejections).toHaveLength(0);
589
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
590
+ expect(spy).toHaveBeenCalledTimes(1);
591
+ });
592
+
593
+ it("should log the failures of the lazy storage", async () => {
594
+ const { client, request, logger } = createFailingClient(rejectingStorage());
595
+
596
+ client.cache.set(request, createCacheResponse({ id: 1 }));
597
+ await client.cache.getLazyResource(cacheKey);
598
+ client.cache.delete(cacheKey);
599
+ await flushPromises();
600
+
601
+ const titles = logger.mock.calls.map(([log]) => log.title);
602
+ expect(titles).toStrictEqual([
603
+ 'Lazy storage "set" failed',
604
+ 'Lazy storage "get" failed',
605
+ 'Lazy storage "delete" failed',
606
+ ]);
607
+ expect(logger.mock.calls.every(([log]) => log.level === "error" && log.module === "Cache")).toBeTrue();
608
+ });
609
+
610
+ it("should return the sync data without waiting for the lazy storage which never answers", () => {
611
+ const { client, request } = createFailingClient({
612
+ get: () => new Promise(() => {}),
613
+ set: () => new Promise(() => {}),
614
+ delete: () => new Promise(() => {}),
615
+ keys: () => new Promise(() => {}),
616
+ });
617
+
618
+ client.cache.set(request, createCacheResponse({ id: 1 }));
619
+
620
+ expect(client.cache.get(cacheKey)?.data).toStrictEqual({ id: 1 });
621
+ });
622
+
623
+ it.each([
624
+ { name: "null", value: null },
625
+ { name: "undefined", value: undefined },
626
+ { name: "empty string", value: "" },
627
+ { name: "zero", value: 0 },
628
+ { name: "text", value: "not a cache value" },
629
+ { name: "number", value: 123 },
630
+ { name: "array", value: [1, 2, 3] },
631
+ { name: "empty object", value: {} },
632
+ { name: "object without the version", value: { data: "value", staleTime: 1000, cacheTime: 1000 } },
633
+ ])("should not load the garbage returned by the lazy storage - $name", async ({ value }) => {
634
+ const { client } = createFailingClient({
635
+ get: async () => value as any,
636
+ set: async () => {},
637
+ delete: async () => {},
638
+ keys: async () => [],
639
+ });
640
+ const spy = vi.fn();
641
+ client.cache.events.onData(spy);
642
+
643
+ const rejections = await getUnhandledRejections(async () => {
644
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
645
+ });
646
+
647
+ expect(rejections).toHaveLength(0);
648
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
649
+ expect(spy).not.toHaveBeenCalled();
650
+ });
651
+
652
+ it("should remove the element without the timestamps from the lazy storage", async () => {
653
+ const deleteSpy = vi.fn(async () => {});
654
+ const { client } = createFailingClient({
655
+ get: async () => ({ version, data: "value" }) as any,
656
+ set: async () => {},
657
+ delete: deleteSpy,
658
+ keys: async () => [],
659
+ });
660
+
661
+ await expect(client.cache.getLazyResource(cacheKey)).resolves.toBeUndefined();
662
+
663
+ expect(deleteSpy).toHaveBeenCalledWith(cacheKey);
664
+ expect(client.cache.storage.get(cacheKey)).toBeUndefined();
665
+ });
666
+ });
667
+ });