@data-client/vue 0.18.1 → 0.18.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 (112) hide show
  1. package/CHANGELOG.md +371 -0
  2. package/README.md +86 -41
  3. package/dist/index.js +223 -158
  4. package/dist/index.umd.min.js +1 -1
  5. package/lib/consumers/refetchTriggers.d.ts +12 -0
  6. package/lib/consumers/refetchTriggers.d.ts.map +1 -0
  7. package/lib/consumers/refetchTriggers.js +9 -0
  8. package/lib/consumers/useCache.d.ts +1 -1
  9. package/lib/consumers/useCache.d.ts.map +1 -1
  10. package/lib/consumers/useCache.js +3 -53
  11. package/lib/consumers/useCacheResponse.d.ts +20 -0
  12. package/lib/consumers/useCacheResponse.d.ts.map +1 -0
  13. package/lib/consumers/useCacheResponse.js +55 -0
  14. package/lib/consumers/useCountRef.d.ts +7 -0
  15. package/lib/consumers/useCountRef.d.ts.map +1 -0
  16. package/lib/consumers/useCountRef.js +10 -0
  17. package/lib/consumers/useDLE.d.ts +1 -1
  18. package/lib/consumers/useDLE.d.ts.map +1 -1
  19. package/lib/consumers/useDLE.js +16 -62
  20. package/lib/consumers/useDebounce.d.ts +1 -1
  21. package/lib/consumers/useDebounce.d.ts.map +1 -1
  22. package/lib/consumers/useDebounce.js +1 -2
  23. package/lib/consumers/useExpired.d.ts +12 -0
  24. package/lib/consumers/useExpired.d.ts.map +1 -0
  25. package/lib/consumers/useExpired.js +19 -0
  26. package/lib/consumers/useFetch.d.ts +8 -11
  27. package/lib/consumers/useFetch.d.ts.map +1 -1
  28. package/lib/consumers/useFetch.js +13 -24
  29. package/lib/consumers/useLive.js +1 -1
  30. package/lib/consumers/useLoading.d.ts +1 -1
  31. package/lib/consumers/useLoading.d.ts.map +1 -1
  32. package/lib/consumers/useLoading.js +1 -2
  33. package/lib/consumers/useQuery.d.ts +1 -1
  34. package/lib/consumers/useQuery.d.ts.map +1 -1
  35. package/lib/consumers/useQuery.js +6 -12
  36. package/lib/consumers/useResponseMeta.d.ts +23 -0
  37. package/lib/consumers/useResponseMeta.d.ts.map +1 -0
  38. package/lib/consumers/useResponseMeta.js +36 -0
  39. package/lib/consumers/useSubscription.js +4 -4
  40. package/lib/consumers/useSuspense.d.ts +1 -1
  41. package/lib/consumers/useSuspense.d.ts.map +1 -1
  42. package/lib/consumers/useSuspense.js +58 -34
  43. package/lib/context.d.ts +1 -1
  44. package/lib/context.d.ts.map +1 -1
  45. package/lib/context.js +3 -3
  46. package/lib/index.d.ts +2 -1
  47. package/lib/index.d.ts.map +1 -1
  48. package/lib/index.js +4 -2
  49. package/lib/internal.d.ts +6 -0
  50. package/lib/internal.d.ts.map +1 -0
  51. package/lib/internal.js +6 -0
  52. package/lib/providers/DataClientPlugin.d.ts +1 -1
  53. package/lib/providers/DataClientPlugin.d.ts.map +1 -1
  54. package/lib/providers/DataClientPlugin.js +16 -4
  55. package/lib/providers/createDataClient.d.ts +10 -4
  56. package/lib/providers/createDataClient.d.ts.map +1 -1
  57. package/lib/providers/createDataClient.js +11 -5
  58. package/lib/providers/getDefaultManagers.d.ts.map +1 -1
  59. package/lib/providers/getDefaultManagers.js +1 -1
  60. package/lib/providers/index.d.ts +2 -1
  61. package/lib/providers/index.d.ts.map +1 -1
  62. package/lib/providers/index.js +1 -1
  63. package/lib/test/MockPlugin.d.ts +1 -1
  64. package/lib/test/MockPlugin.d.ts.map +1 -1
  65. package/lib/test/MockPlugin.js +1 -1
  66. package/lib/test/index.d.ts +2 -1
  67. package/lib/test/index.d.ts.map +1 -1
  68. package/lib/test/index.js +1 -1
  69. package/lib/test/mountDataClient.d.ts +5 -3
  70. package/lib/test/mountDataClient.d.ts.map +1 -1
  71. package/lib/test/mountDataClient.js +15 -10
  72. package/lib/test/renderDataCompose.d.ts +10 -4
  73. package/lib/test/renderDataCompose.d.ts.map +1 -1
  74. package/lib/test/renderDataCompose.js +2 -3
  75. package/package.json +20 -5
  76. package/src/__tests__/__snapshots__/context.test.ts.snap +2 -2
  77. package/src/__tests__/context.test.ts +1 -1
  78. package/src/__tests__/integration-garbage-collection.web.ts +80 -4
  79. package/src/__tests__/useCache.web.ts +160 -93
  80. package/src/__tests__/useDLE.web.ts +204 -96
  81. package/src/__tests__/useFetch.web.ts +100 -37
  82. package/src/__tests__/useQuery.web.ts +60 -50
  83. package/src/__tests__/useSubscription.web.ts +74 -75
  84. package/src/__tests__/useSuspense.web.ts +455 -46
  85. package/src/consumers/refetchTriggers.ts +22 -0
  86. package/src/consumers/useCache.ts +7 -70
  87. package/src/consumers/useCacheResponse.ts +56 -0
  88. package/src/consumers/useCountRef.ts +15 -0
  89. package/src/consumers/useDLE.ts +24 -83
  90. package/src/consumers/useDebounce.ts +2 -1
  91. package/src/consumers/useExpired.ts +26 -0
  92. package/src/consumers/useFetch.ts +34 -49
  93. package/src/consumers/useLive.ts +1 -1
  94. package/src/consumers/useLoading.ts +2 -1
  95. package/src/consumers/useQuery.ts +10 -13
  96. package/src/consumers/useResponseMeta.ts +41 -0
  97. package/src/consumers/useSubscription.ts +3 -3
  98. package/src/consumers/useSuspense.ts +66 -58
  99. package/src/context.ts +4 -3
  100. package/src/index.ts +7 -1
  101. package/src/internal.ts +12 -0
  102. package/src/providers/DataClientPlugin.ts +17 -3
  103. package/src/providers/__tests__/DataClientPlugin.test.ts +40 -1
  104. package/src/providers/createDataClient.ts +15 -5
  105. package/src/providers/getDefaultManagers.ts +2 -6
  106. package/src/providers/index.ts +2 -5
  107. package/src/test/MockPlugin.ts +3 -3
  108. package/src/test/README.md +10 -304
  109. package/src/test/__tests__/mountDataClient.test.ts +38 -0
  110. package/src/test/index.ts +2 -1
  111. package/src/test/mountDataClient.ts +22 -17
  112. package/src/test/renderDataCompose.ts +11 -7
@@ -1,13 +1,27 @@
1
- import { Endpoint } from '@data-client/endpoint';
1
+ import { Endpoint, Invalidate } from '@data-client/endpoint';
2
2
  import nock from 'nock';
3
- import { computed, defineComponent, h, nextTick, reactive } from 'vue';
3
+ import {
4
+ computed,
5
+ defineComponent,
6
+ h,
7
+ nextTick,
8
+ onErrorCaptured,
9
+ reactive,
10
+ } from 'vue';
11
+ import type { MaybeRefOrGetter } from 'vue';
4
12
 
5
13
  import {
6
14
  CoolerArticleResource,
7
15
  CoolerArticle,
8
16
  } from '../../../../__tests__/new';
9
17
  import useSuspense from '../consumers/useSuspense';
10
- import { renderDataCompose, mountDataClient } from '../test';
18
+ import { renderDataCompose, mountDataClient, mockInitialState } from '../test';
19
+
20
+ // Each arg form a composable accepts that should re-evaluate reactively
21
+ const argForms: [string, <T>(fn: () => T) => MaybeRefOrGetter<T>][] = [
22
+ ['computed', fn => computed(fn)],
23
+ ['getter', fn => fn],
24
+ ];
11
25
 
12
26
  // Minimal shared fixture (copied from React test fixtures)
13
27
  const payload = {
@@ -91,13 +105,9 @@ describe('vue useSuspense()', () => {
91
105
  });
92
106
 
93
107
  it('re-renders when controller.setResponse() updates data', async () => {
94
- const { result, controller, waitForNextUpdate, cleanup } =
95
- await renderDataCompose(() =>
96
- useSuspense(CoolerArticleResource.get, { id: payload.id }),
97
- );
98
-
99
- // Wait for initial render
100
- await waitForNextUpdate();
108
+ const { result, controller, cleanup } = await renderDataCompose(() =>
109
+ useSuspense(CoolerArticleResource.get, { id: payload.id }),
110
+ );
101
111
 
102
112
  // Await the promise once to get the reactive ComputedRef
103
113
  const articleRef = await result;
@@ -126,13 +136,9 @@ describe('vue useSuspense()', () => {
126
136
  });
127
137
 
128
138
  it('re-renders when controller.fetch() mutates data', async () => {
129
- const { result, controller, waitForNextUpdate, cleanup } =
130
- await renderDataCompose(() =>
131
- useSuspense(CoolerArticleResource.get, { id: payload.id }),
132
- );
133
-
134
- // Wait for initial render
135
- await waitForNextUpdate();
139
+ const { result, controller, cleanup } = await renderDataCompose(() =>
140
+ useSuspense(CoolerArticleResource.get, { id: payload.id }),
141
+ );
136
142
 
137
143
  // Await the promise once to get the reactive ComputedRef
138
144
  const articleRef = await result;
@@ -255,53 +261,357 @@ describe('vue useSuspense()', () => {
255
261
  }));
256
262
  });
257
263
 
258
- it('should initially resolve, then when args are null should return undefined, then back to resolving', async () => {
259
- const props = reactive({ id: payload.id as number | null });
260
- const { result, allSettled, waitForNextUpdate, cleanup } =
261
- await renderDataCompose(
262
- (props: { id: number | null }) =>
263
- useSuspense(
264
- CoolerArticleResource.get,
265
- computed(() => (props.id !== null ? { id: props.id } : null)),
266
- ),
267
- { props },
268
- );
264
+ it('keeps previous data while new args are loading', async () => {
265
+ const resolvers: Record<number, (value: any) => void> = {};
266
+ const ControlledEndpoint = new Endpoint(
267
+ ({ id }: { id: number }) =>
268
+ new Promise(resolve => {
269
+ resolvers[id] = resolve;
270
+ }),
271
+ { schema: CoolerArticle, name: 'KeepPreviousEndpoint' },
272
+ );
269
273
 
270
- // Wait for initial render
271
- await waitForNextUpdate();
274
+ const errorSpy = jest.fn();
275
+ const ArticleTitle = defineComponent({
276
+ name: 'ArticleTitle',
277
+ props: { id: { type: Number, required: true } },
278
+ async setup(props: { id: number }) {
279
+ const article = await useSuspense(
280
+ ControlledEndpoint,
281
+ computed(() => ({ id: props.id })),
282
+ );
283
+ // no optional chaining: crashes if data is ever undefined
284
+ return () => h('h3', article.value.title);
285
+ },
286
+ });
287
+ const Parent = defineComponent({
288
+ name: 'Parent',
289
+ props: { id: { type: Number, required: true } },
290
+ setup(props: { id: number }) {
291
+ onErrorCaptured(e => {
292
+ errorSpy(e);
293
+ return false;
294
+ });
295
+ return () => h(ArticleTitle, { id: props.id });
296
+ },
297
+ });
272
298
 
273
- // Await the promise once to get the reactive ComputedRef
299
+ const props = reactive({ id: payload.id });
300
+ const { wrapper, cleanup } = mountDataClient(Parent, { props });
301
+
302
+ await flushUntil(wrapper, () => !!resolvers[payload.id]);
303
+ resolvers[payload.id](payload);
304
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
305
+ expect(wrapper.find('h3').text()).toBe(payload.title);
306
+
307
+ props.id = payload2.id;
308
+ await flushUntil(wrapper, () => !!resolvers[payload2.id]);
309
+ await nextTick();
310
+
311
+ // still showing previous data while the new fetch is in flight
312
+ expect(wrapper.find('h3').text()).toBe(payload.title);
313
+ expect(errorSpy).not.toHaveBeenCalled();
314
+
315
+ resolvers[payload2.id](payload2);
316
+ await flushUntil(
317
+ wrapper,
318
+ () => wrapper.find('h3').text() === payload2.title,
319
+ );
320
+ expect(wrapper.find('h3').text()).toBe(payload2.title);
321
+ expect(errorSpy).not.toHaveBeenCalled();
322
+
323
+ cleanup();
324
+ });
325
+
326
+ it('throws fetch errors for new args from the returned ref', async () => {
327
+ const props = reactive({ id: payload.id });
328
+ const { result, allSettled, cleanup } = await renderDataCompose(
329
+ (props: { id: number }) =>
330
+ useSuspense(
331
+ CoolerArticleResource.get,
332
+ computed(() => ({ id: props.id })),
333
+ ),
334
+ {
335
+ props,
336
+ resolverFixtures: [
337
+ {
338
+ endpoint: CoolerArticleResource.get,
339
+ args: [{ id: payload.id }],
340
+ response: payload,
341
+ },
342
+ {
343
+ endpoint: CoolerArticleResource.get,
344
+ args: [{ id: payload2.id }],
345
+ response: new Error('Not Found'),
346
+ error: true,
347
+ },
348
+ ],
349
+ },
350
+ );
274
351
  const articleRef = await result;
352
+ expect(articleRef.value.title).toBe(payload.title);
275
353
 
276
- expect(articleRef).toBeDefined();
354
+ props.id = payload2.id;
355
+ await allSettled();
277
356
 
278
- // Verify initial values
279
- expect(articleRef.value?.title).toBe(payload.title);
280
- expect(articleRef.value?.content).toBe(payload.content);
357
+ expect(() => articleRef.value).toThrow('Not Found');
358
+ // every read throws, not just the first
359
+ expect(() => articleRef.value).toThrow('Not Found');
281
360
 
282
- // Change to null - the ComputedRef should reactively become undefined
283
- props.id = null;
361
+ // recovers when args change back
362
+ props.id = payload.id;
284
363
  await nextTick();
364
+ expect(articleRef.value.title).toBe(payload.title);
285
365
 
286
- // The same ComputedRef should now have undefined value
287
- expect(articleRef.value).toBeUndefined();
366
+ cleanup();
367
+ });
368
+
369
+ it('sends fetch errors for new args to onErrorCaptured', async () => {
370
+ const settlers: Record<
371
+ number,
372
+ { resolve: (value: any) => void; reject: (e: any) => void }
373
+ > = {};
374
+ const ControlledEndpoint = new Endpoint(
375
+ ({ id }: { id: number }) =>
376
+ new Promise((resolve, reject) => {
377
+ settlers[id] = { resolve, reject };
378
+ }),
379
+ { schema: CoolerArticle, name: 'ErrorTransitionEndpoint' },
380
+ );
381
+
382
+ const errorSpy = jest.fn();
383
+ const ArticleTitle = defineComponent({
384
+ name: 'ArticleTitle',
385
+ props: { id: { type: Number, required: true } },
386
+ async setup(props: { id: number }) {
387
+ const article = await useSuspense(
388
+ ControlledEndpoint,
389
+ computed(() => ({ id: props.id })),
390
+ );
391
+ return () => h('h3', article.value.title);
392
+ },
393
+ });
394
+ const Parent = defineComponent({
395
+ name: 'Parent',
396
+ props: { id: { type: Number, required: true } },
397
+ setup(props: { id: number }) {
398
+ onErrorCaptured(e => {
399
+ errorSpy(e);
400
+ return false;
401
+ });
402
+ return () => h(ArticleTitle, { id: props.id });
403
+ },
404
+ });
405
+
406
+ const props = reactive({ id: payload.id });
407
+ const { wrapper, cleanup } = mountDataClient(Parent, { props });
408
+
409
+ await flushUntil(wrapper, () => !!settlers[payload.id]);
410
+ settlers[payload.id].resolve(payload);
411
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
412
+ expect(wrapper.find('h3').text()).toBe(payload.title);
288
413
 
289
- // Change back to valid id - should resolve the new data
290
414
  props.id = payload2.id;
415
+ await flushUntil(wrapper, () => !!settlers[payload2.id]);
416
+ const error = Object.assign(new Error('Not Found'), { status: 404 });
417
+ settlers[payload2.id].reject(error);
418
+ await flushUntil(wrapper, () => errorSpy.mock.calls.length > 0);
419
+
420
+ expect(errorSpy).toHaveBeenCalled();
421
+ // render threw too, rather than showing the previous args' data
422
+ expect(wrapper.find('h3').exists()).toBe(false);
423
+ // the fetch error itself, not a crash from rendering undefined data
424
+ for (const [captured] of errorSpy.mock.calls) {
425
+ expect(captured).toBe(error);
426
+ }
427
+
428
+ cleanup();
429
+ });
430
+
431
+ // first fetch resolves; later fetches stay in flight until resolveRefetch()
432
+ function heldRefetchEndpoint(name: string, options: object = {}) {
433
+ let fetches = 0;
434
+ let resolveRefetch: (value: any) => void = () => {};
435
+ const endpoint = new Endpoint(
436
+ ({ id }: { id: number }) =>
437
+ fetches++ === 0 ?
438
+ Promise.resolve({ ...payload, id })
439
+ : new Promise(resolve => {
440
+ resolveRefetch = resolve;
441
+ }),
442
+ { schema: CoolerArticle, name, ...options },
443
+ );
444
+ return {
445
+ endpoint,
446
+ fetches: () => fetches,
447
+ resolveRefetch: (value: any) => resolveRefetch(value),
448
+ };
449
+ }
450
+
451
+ async function mountArticle(
452
+ endpoint: ReturnType<typeof heldRefetchEndpoint>['endpoint'],
453
+ ) {
454
+ const { result, controller, cleanup } = await renderDataCompose(() =>
455
+ useSuspense(endpoint, { id: payload.id }),
456
+ );
457
+ const articleRef = await result;
458
+ expect(articleRef.value.title).toBe(payload.title);
459
+ return { articleRef, controller, cleanup };
460
+ }
461
+
462
+ const staleOptions = { dataExpiryLength: 20, invalidIfStale: true };
463
+
464
+ it('shows store updates once invalidIfStale data goes stale', async () => {
465
+ const { endpoint, fetches } = heldRefetchEndpoint(
466
+ 'StaleEndpoint',
467
+ staleOptions,
468
+ );
469
+ const { articleRef, controller, cleanup } = await mountArticle(endpoint);
470
+
471
+ // let the data go stale without anything triggering a refetch
472
+ await new Promise(resolve => setTimeout(resolve, 50));
473
+ await controller.set(
474
+ CoolerArticle,
475
+ { id: payload.id },
476
+ { ...payload, title: 'edited' },
477
+ );
291
478
  await nextTick();
292
479
 
293
- // Wait for the fetch to complete
294
- await allSettled();
480
+ expect(fetches()).toBe(1);
481
+ expect(articleRef.value.title).toBe('edited');
482
+
483
+ cleanup();
484
+ });
485
+
486
+ it('shows new args data that went stale before it was read', async () => {
487
+ const LazyEndpoint = new Endpoint(
488
+ ({ id }: { id: number }) =>
489
+ Promise.resolve(id === payload.id ? payload : payload2),
490
+ { schema: CoolerArticle, name: 'LazyEndpoint', ...staleOptions },
491
+ );
492
+ const props = reactive({ id: payload.id });
493
+ const { result, cleanup } = await renderDataCompose(
494
+ (props: { id: number }) =>
495
+ useSuspense(
496
+ LazyEndpoint,
497
+ computed(() => ({ id: props.id })),
498
+ ),
499
+ { props },
500
+ );
501
+ const articleRef = await result;
502
+ expect(articleRef.value.title).toBe(payload.title);
503
+
504
+ // new args resolve and go stale without the result being read in between
505
+ props.id = payload2.id;
506
+ await nextTick();
507
+ await new Promise(resolve => setTimeout(resolve, 0));
295
508
  await nextTick();
509
+ await new Promise(resolve => setTimeout(resolve, 50));
296
510
 
297
- // The ComputedRef should now have the new article data
298
- expect(articleRef).toBeDefined();
299
- expect(articleRef?.value?.title).toBe(payload2.title);
300
- expect(articleRef.value?.content).toBe(payload2.content);
511
+ expect(articleRef.value.title).toBe(payload2.title);
512
+ cleanup();
513
+ });
514
+
515
+ it('shows store updates while refetching the same args', async () => {
516
+ const { endpoint, fetches, resolveRefetch } = heldRefetchEndpoint(
517
+ 'RefetchEndpoint',
518
+ staleOptions,
519
+ );
520
+ const { articleRef, controller, cleanup } = await mountArticle(endpoint);
521
+
522
+ // expiring the data makes the hook refetch the same args
523
+ await controller.expireAll({
524
+ testKey: key => key.startsWith('RefetchEndpoint'),
525
+ });
526
+ await nextTick();
527
+ expect(fetches()).toBe(2);
528
+ await controller.set(
529
+ CoolerArticle,
530
+ { id: payload.id },
531
+ { ...payload, title: 'edited' },
532
+ );
533
+ await nextTick();
534
+
535
+ expect(fetches()).toBe(2);
536
+ expect(articleRef.value.title).toBe('edited');
537
+
538
+ resolveRefetch({ ...payload, title: 'edited' });
539
+ await new Promise(resolve => setTimeout(resolve, 0));
540
+ cleanup();
541
+ });
301
542
 
543
+ it('keeps previous data while refetching a deleted entity', async () => {
544
+ const { endpoint, fetches, resolveRefetch } =
545
+ heldRefetchEndpoint('DeletedEndpoint');
546
+ const { articleRef, controller, cleanup } = await mountArticle(endpoint);
547
+
548
+ const DeleteEndpoint = new Endpoint(
549
+ ({ id }: { id: number }) => Promise.resolve({ id }),
550
+ {
551
+ schema: new Invalidate(CoolerArticle),
552
+ sideEffect: true,
553
+ name: 'DeleteArticle',
554
+ },
555
+ );
556
+ await controller.fetch(DeleteEndpoint, { id: payload.id });
557
+ await nextTick();
558
+ await nextTick();
559
+
560
+ expect(fetches()).toBe(2);
561
+ expect(articleRef.value.title).toBe(payload.title);
562
+
563
+ resolveRefetch({ ...payload, title: 'restored' });
564
+ await new Promise(resolve => setTimeout(resolve, 0));
565
+ await nextTick();
566
+ expect(articleRef.value.title).toBe('restored');
302
567
  cleanup();
303
568
  });
304
569
 
570
+ it.each(argForms)(
571
+ 'should initially resolve, then when args are null should return undefined, then back to resolving (%s args)',
572
+ async (_, toArg) => {
573
+ const props = reactive({ id: payload.id as number | null });
574
+ const { result, allSettled, cleanup } = await renderDataCompose(
575
+ (props: { id: number | null }) =>
576
+ useSuspense(
577
+ CoolerArticleResource.get,
578
+ toArg(() => (props.id !== null ? { id: props.id } : null)),
579
+ ),
580
+ { props },
581
+ );
582
+
583
+ // Await the promise once to get the reactive ComputedRef
584
+ const articleRef = await result;
585
+
586
+ expect(articleRef).toBeDefined();
587
+
588
+ // Verify initial values
589
+ expect(articleRef.value?.title).toBe(payload.title);
590
+ expect(articleRef.value?.content).toBe(payload.content);
591
+
592
+ // Change to null - the ComputedRef should reactively become undefined
593
+ props.id = null;
594
+ await nextTick();
595
+
596
+ // The same ComputedRef should now have undefined value
597
+ expect(articleRef.value).toBeUndefined();
598
+
599
+ // Change back to valid id - should resolve the new data
600
+ props.id = payload2.id;
601
+ await nextTick();
602
+
603
+ // Wait for the fetch to complete
604
+ await allSettled();
605
+
606
+ // The ComputedRef should now have the new article data
607
+ expect(articleRef).toBeDefined();
608
+ expect(articleRef?.value?.title).toBe(payload2.title);
609
+ expect(articleRef.value?.content).toBe(payload2.content);
610
+
611
+ cleanup();
612
+ },
613
+ );
614
+
305
615
  it('should initiate second fetch when props change even if first promise never resolves', async () => {
306
616
  let fetchInitialCalled = false;
307
617
  let fetchFinalCalled = false;
@@ -361,4 +671,103 @@ describe('vue useSuspense()', () => {
361
671
 
362
672
  cleanup();
363
673
  });
674
+
675
+ it('should not refetch stale data on store updates that keep expiry unchanged', async () => {
676
+ const fetchMock = jest.fn(async ({ id }: { id: number }) => ({
677
+ ...payload,
678
+ id,
679
+ }));
680
+ const staleEndpoint = new Endpoint(fetchMock, {
681
+ schema: CoolerArticle,
682
+ dataExpiryLength: 20,
683
+ name: 'staleArticle',
684
+ });
685
+
686
+ const { result, controller, cleanup } = await renderDataCompose(() =>
687
+ useSuspense(staleEndpoint, { id: 77 }),
688
+ );
689
+ const articleRef = await result;
690
+ expect(fetchMock).toHaveBeenCalledTimes(1);
691
+
692
+ // let data become stale
693
+ await new Promise(resolve => setTimeout(resolve, 50));
694
+
695
+ await controller.set(
696
+ CoolerArticle,
697
+ { id: 77 },
698
+ { id: 77, title: 'edited' },
699
+ );
700
+ await nextTick();
701
+ await new Promise(resolve => setTimeout(resolve, 0));
702
+
703
+ // the store update should not trigger a refetch that overwrites the set
704
+ expect(fetchMock).toHaveBeenCalledTimes(1);
705
+ expect(articleRef.value?.title).toBe('edited');
706
+
707
+ cleanup();
708
+ });
709
+ describe('stale data on mount', () => {
710
+ // mounts with cached data that has already expired; the refetch stays in flight until resolveFetch()
711
+ async function mountStale(invalidIfStale: boolean) {
712
+ let resolveFetch: (value: any) => void = () => {};
713
+ const fetchMock = jest.fn(
714
+ (_args: { id: number }) =>
715
+ new Promise<typeof payload>(resolve => (resolveFetch = resolve)),
716
+ );
717
+ const endpoint = new Endpoint(fetchMock, {
718
+ schema: CoolerArticle,
719
+ invalidIfStale,
720
+ name: 'staleOnMount',
721
+ });
722
+ const args = { id: payload.id };
723
+ const state = mockInitialState([
724
+ { endpoint, args: [args], response: payload },
725
+ ]);
726
+ const key = endpoint.key(args);
727
+ // long expired (0 would fall back to entity expiry)
728
+ const initialState = {
729
+ ...state,
730
+ meta: { ...state.meta, [key]: { ...state.meta[key], expiresAt: 1 } },
731
+ };
732
+
733
+ const { result, cleanup } = await renderDataCompose(
734
+ () => useSuspense(endpoint, args),
735
+ { initialState },
736
+ );
737
+ expect(fetchMock).toHaveBeenCalledTimes(1);
738
+ return {
739
+ result,
740
+ cleanup,
741
+ resolveFetch: (value: any) => resolveFetch(value),
742
+ };
743
+ }
744
+
745
+ it('shows stale data immediately and revalidates in the background', async () => {
746
+ const { result, cleanup, resolveFetch } = await mountStale(false);
747
+
748
+ // resolves without waiting for the refetch
749
+ const articleRef = await result;
750
+ expect(articleRef.value?.title).toBe(payload.title);
751
+
752
+ resolveFetch({ ...payload, title: 'revalidated' });
753
+ await flushUntil(null, () => articleRef.value?.title === 'revalidated');
754
+ expect(articleRef.value?.title).toBe('revalidated');
755
+
756
+ cleanup();
757
+ });
758
+
759
+ it('suspends on stale invalidIfStale data until the refetch resolves', async () => {
760
+ const { result, cleanup, resolveFetch } = await mountStale(true);
761
+
762
+ await expect(
763
+ Promise.race([result, Promise.resolve('pending')]),
764
+ ).resolves.toBe('pending');
765
+
766
+ resolveFetch({ ...payload, title: 'revalidated' });
767
+ const articleRef = await result;
768
+ expect(articleRef.value?.title).toBe('revalidated');
769
+
770
+ cleanup();
771
+ });
772
+ });
364
773
  });
@@ -0,0 +1,22 @@
1
+ import type { ExpiryStatus, State } from '@data-client/core';
2
+ import type { Ref } from 'vue';
3
+
4
+ /** Watch sources whose changes may require a refetch.
5
+ *
6
+ * Multi-source form so Vue compares each value; a getter returning a new array
7
+ * would fire on every store update and refetch stale data unexpectedly.
8
+ */
9
+ export default function refetchTriggers(
10
+ responseMeta: Readonly<
11
+ Ref<{ readonly expiresAt: number; readonly expiryStatus: ExpiryStatus }>
12
+ >,
13
+ stateRef: Readonly<Ref<State<unknown>>>,
14
+ argsKey: Readonly<Ref<string>>,
15
+ ) {
16
+ return [
17
+ () => responseMeta.value.expiresAt,
18
+ () => responseMeta.value.expiryStatus,
19
+ () => stateRef.value.lastReset,
20
+ argsKey,
21
+ ] as const;
22
+ }
@@ -5,14 +5,13 @@ import type {
5
5
  FetchFunction,
6
6
  ResolveType,
7
7
  } from '@data-client/core';
8
- import { ExpiryStatus } from '@data-client/core';
9
- import { computed, unref, watch, type ComputedRef } from 'vue';
8
+ import type { ComputedRef } from 'vue';
10
9
 
11
- import { useController, injectState } from '../context.js';
12
10
  import type {
13
11
  MaybeRefsOrGetters,
14
12
  MaybeRefsOrGettersNullable,
15
13
  } from '../types.js';
14
+ import useCacheResponse from './useCacheResponse.js';
16
15
 
17
16
  /**
18
17
  * Read an Endpoint's response if it is ready.
@@ -52,71 +51,9 @@ export default function useCache<
52
51
  : DenormalizeNullable<E['schema']>
53
52
  >;
54
53
 
55
- export default function useCache(endpoint: any, ...args: any[]): any {
56
- const stateRef = injectState();
57
- const controller = useController();
58
-
59
- // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger updates.
60
- const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
61
-
62
- // Compute a key that changes when args change (including reactive props)
63
- const argsKey = computed(() =>
64
- resolvedArgs.value[0] !== null ? endpoint.key(...resolvedArgs.value) : '',
65
- );
66
-
67
- // Compute response meta reactively so we can respond to store updates
68
- const responseMeta = computed(() => {
69
- return controller.getResponseMeta(
70
- endpoint,
71
- ...resolvedArgs.value,
72
- stateRef.value,
73
- );
74
- });
75
-
76
- // If we are hard invalid we must fetch regardless of triggering or staleness
77
- const forceFetch = computed(
78
- () => responseMeta.value.expiryStatus === ExpiryStatus.Invalid,
79
- );
80
-
81
- /*********** This block is to ensure results are only filled when they would not suspend **************/
82
- // This computation reflects the behavior of useSuspense/useFetch
83
- // It only changes the value when expiry or params change.
84
- // This way, random unrelated re-renders don't cause the concept of expiry
85
- // to change
86
- const expired = computed(() => {
87
- return (
88
- (Date.now() > responseMeta.value.expiresAt || forceFetch.value) &&
89
- argsKey.value
90
- );
91
- });
92
-
93
- // fully "valid" data will not suspend/loading even if it is not fresh
94
- const loading = computed(
95
- () =>
96
- responseMeta.value.expiryStatus !== ExpiryStatus.Valid && expired.value,
97
- );
98
- /****************************************************************************************************/
99
-
100
- // Maintain GC refcounts on data mount/changes
101
- watch(
102
- () => responseMeta.value.data,
103
- (_newVal, _oldVal, onCleanup) => {
104
- const decrement = responseMeta.value.countRef();
105
- onCleanup(() => decrement());
106
- },
107
- { immediate: true },
108
- );
109
-
110
- return computed(() => {
111
- // if useSuspense() would suspend, don't include entities from cache
112
- if (loading.value) {
113
- if (!endpoint.schema) return undefined;
114
- // TODO: use getResponse() once it just returns data
115
- return controller.getResponseMeta(endpoint, ...resolvedArgs.value, {
116
- ...stateRef.value,
117
- entities: {},
118
- }).data as any;
119
- }
120
- return responseMeta.value.data;
121
- });
54
+ export default function useCache(
55
+ endpoint: any,
56
+ ...args: any[]
57
+ ): ComputedRef<unknown> {
58
+ return useCacheResponse(endpoint, args).data;
122
59
  }