@data-client/vue 0.2.0 → 0.3.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 (98) hide show
  1. package/README.md +1 -24
  2. package/dist/index.js +185 -35
  3. package/dist/index.umd.min.js +1 -1
  4. package/lib/consumers/index.d.ts +2 -0
  5. package/lib/consumers/index.d.ts.map +1 -1
  6. package/lib/consumers/index.js +3 -1
  7. package/lib/consumers/useCache.d.ts +12 -0
  8. package/lib/consumers/useCache.d.ts.map +1 -0
  9. package/lib/consumers/useCache.js +63 -0
  10. package/lib/consumers/useDLE.d.ts +18 -0
  11. package/lib/consumers/useDLE.d.ts.map +1 -0
  12. package/lib/consumers/useDLE.js +88 -0
  13. package/lib/consumers/useFetch.d.ts +3 -2
  14. package/lib/consumers/useFetch.d.ts.map +1 -1
  15. package/lib/consumers/useFetch.js +10 -8
  16. package/lib/consumers/useLive.d.ts +3 -2
  17. package/lib/consumers/useLive.d.ts.map +1 -1
  18. package/lib/consumers/useLive.js +1 -1
  19. package/lib/consumers/useQuery.d.ts +3 -2
  20. package/lib/consumers/useQuery.d.ts.map +1 -1
  21. package/lib/consumers/useQuery.js +7 -3
  22. package/lib/consumers/useSubscription.d.ts +2 -1
  23. package/lib/consumers/useSubscription.d.ts.map +1 -1
  24. package/lib/consumers/useSubscription.js +1 -2
  25. package/lib/consumers/useSuspense.d.ts +3 -2
  26. package/lib/consumers/useSuspense.d.ts.map +1 -1
  27. package/lib/consumers/useSuspense.js +15 -20
  28. package/lib/index.d.ts +1 -0
  29. package/lib/index.d.ts.map +1 -1
  30. package/lib/index.js +1 -1
  31. package/lib/providers/DataClientPlugin.d.ts +6 -0
  32. package/lib/providers/DataClientPlugin.d.ts.map +1 -1
  33. package/lib/providers/DataClientPlugin.js +15 -11
  34. package/lib/providers/index.d.ts +1 -1
  35. package/lib/providers/index.d.ts.map +1 -1
  36. package/lib/providers/index.js +1 -1
  37. package/lib/test/index.d.ts +3 -4
  38. package/lib/test/index.d.ts.map +1 -1
  39. package/lib/test/index.js +3 -5
  40. package/lib/test/mountDataClient.d.ts +29 -0
  41. package/lib/test/mountDataClient.d.ts.map +1 -0
  42. package/lib/test/mountDataClient.js +114 -0
  43. package/lib/test/renderDataCompose.d.ts +19 -0
  44. package/lib/test/renderDataCompose.d.ts.map +1 -0
  45. package/lib/test/renderDataCompose.js +135 -0
  46. package/lib/types.d.ts +10 -0
  47. package/lib/types.d.ts.map +1 -0
  48. package/lib/types.js +2 -0
  49. package/package.json +6 -6
  50. package/src/__tests__/context.test.ts +195 -0
  51. package/src/__tests__/integration-garbage-collection.web.ts +12 -15
  52. package/src/__tests__/useCache.web.ts +391 -0
  53. package/src/__tests__/useDLE.web.ts +660 -0
  54. package/src/__tests__/useQuery.web.ts +332 -50
  55. package/src/__tests__/useSubscription.web.ts +233 -119
  56. package/src/__tests__/useSuspense.web.ts +176 -50
  57. package/src/consumers/index.ts +2 -0
  58. package/src/consumers/useCache.ts +122 -0
  59. package/src/consumers/useDLE.ts +160 -0
  60. package/src/consumers/useFetch.ts +24 -13
  61. package/src/consumers/useLive.ts +6 -2
  62. package/src/consumers/useQuery.ts +14 -5
  63. package/src/consumers/useSubscription.ts +5 -1
  64. package/src/consumers/useSuspense.ts +29 -17
  65. package/src/index.ts +4 -0
  66. package/src/providers/DataClientPlugin.ts +25 -10
  67. package/src/providers/__tests__/DataClientPlugin.test.ts +204 -4
  68. package/src/providers/__tests__/createDataClient.test.ts +234 -0
  69. package/src/providers/__tests__/getDefaultManagers.test.ts +180 -0
  70. package/src/providers/index.ts +5 -1
  71. package/src/test/README.md +77 -16
  72. package/src/test/__tests__/mountDataClient.test.ts +426 -0
  73. package/src/test/__tests__/renderDataCompose.test.ts +586 -0
  74. package/src/test/index.ts +3 -9
  75. package/src/test/mountDataClient.ts +169 -0
  76. package/src/test/renderDataCompose.ts +150 -0
  77. package/src/types.ts +11 -0
  78. package/ts3.4/consumers/index.d.ts +2 -0
  79. package/ts3.4/consumers/useCache.d.ts +14 -0
  80. package/ts3.4/consumers/useDLE.d.ts +20 -0
  81. package/ts3.4/consumers/useFetch.d.ts +3 -6
  82. package/ts3.4/consumers/useLive.d.ts +3 -6
  83. package/ts3.4/consumers/useQuery.d.ts +3 -2
  84. package/ts3.4/consumers/useSubscription.d.ts +2 -3
  85. package/ts3.4/consumers/useSuspense.d.ts +3 -6
  86. package/ts3.4/index.d.ts +1 -0
  87. package/ts3.4/providers/DataClientPlugin.d.ts +6 -0
  88. package/ts3.4/providers/index.d.ts +1 -1
  89. package/ts3.4/test/index.d.ts +3 -4
  90. package/ts3.4/test/mountDataClient.d.ts +29 -0
  91. package/ts3.4/test/renderDataCompose.d.ts +19 -0
  92. package/ts3.4/types.d.ts +10 -0
  93. package/lib/test/renderDataClient.d.ts +0 -40
  94. package/lib/test/renderDataClient.d.ts.map +0 -1
  95. package/lib/test/renderDataClient.js +0 -264
  96. package/src/__tests__/__snapshots__/useSubscription.web.ts.snap +0 -7
  97. package/src/test/renderDataClient.ts +0 -316
  98. package/ts3.4/test/renderDataClient.d.ts +0 -40
@@ -1,12 +1,13 @@
1
+ import { Endpoint } from '@data-client/endpoint';
1
2
  import nock from 'nock';
2
- import { defineComponent, h, nextTick } from 'vue';
3
+ import { computed, defineComponent, h, nextTick, reactive } from 'vue';
3
4
 
4
- import { CoolerArticleResource } from '../../../../__tests__/new';
5
- import useSuspense from '../consumers/useSuspense';
6
5
  import {
7
- renderDataComposable,
8
- renderDataClient,
9
- } from '../test/renderDataClient';
6
+ CoolerArticleResource,
7
+ CoolerArticle,
8
+ } from '../../../../__tests__/new';
9
+ import useSuspense from '../consumers/useSuspense';
10
+ import { renderDataCompose, mountDataClient } from '../test';
10
11
 
11
12
  // Minimal shared fixture (copied from React test fixtures)
12
13
  const payload = {
@@ -62,44 +63,40 @@ describe('vue useSuspense()', () => {
62
63
  nock.cleanAll();
63
64
  });
64
65
 
65
- // No need for ProvideWrapper anymore since Suspense is integrated into renderDataClient
66
+ // No need for ProvideWrapper anymore since Suspense is integrated into mountDataClient
66
67
 
67
68
  it('suspends on empty store, then renders after fetch resolves', async () => {
68
- const { result, waitForNextUpdate, cleanup } = renderDataComposable(() =>
69
+ const { result, cleanup } = await renderDataCompose(() =>
69
70
  useSuspense(CoolerArticleResource.get, { id: payload.id }),
70
71
  );
71
72
 
72
- // Initially should be undefined while suspended (React-like interface)
73
- expect(result.current).toBeUndefined();
74
-
75
- // Wait for the composable to resolve
76
- await waitForNextUpdate();
77
-
78
- // Now should have the actual data (useSuspense returns a Promise that resolves to ComputedRef)
79
- expect(result.current).toBeDefined();
80
- expect(result.current).toBeInstanceOf(Promise);
73
+ // Should have the Promise (suspension in Vue 3 returns a Promise)
74
+ expect(result).toBeDefined();
75
+ expect(result).toBeInstanceOf(Promise);
81
76
 
82
- // Wait for the promise to resolve
83
- const articleRef = await result.current;
84
- expect(articleRef!.value.title).toBe(payload.title);
85
- expect(articleRef!.value.content).toBe(payload.content);
77
+ // Await the promise once to get the reactive ComputedRef
78
+ const articleRef = await result;
79
+ expect(articleRef.value.title).toBe(payload.title);
80
+ expect(articleRef.value.content).toBe(payload.content);
86
81
 
87
82
  cleanup();
88
83
  });
89
84
 
90
85
  it('re-renders when controller.setResponse() updates data', async () => {
91
86
  const { result, controller, waitForNextUpdate, cleanup } =
92
- renderDataComposable(() =>
87
+ await renderDataCompose(() =>
93
88
  useSuspense(CoolerArticleResource.get, { id: payload.id }),
94
89
  );
95
90
 
96
91
  // Wait for initial render
97
92
  await waitForNextUpdate();
98
93
 
94
+ // Await the promise once to get the reactive ComputedRef
95
+ const articleRef = await result;
96
+
99
97
  // Verify initial values
100
- const initialArticleRef = await result.current;
101
- expect(initialArticleRef!.value.title).toBe(payload.title);
102
- expect(initialArticleRef!.value.content).toBe(payload.content);
98
+ expect(articleRef.value.title).toBe(payload.title);
99
+ expect(articleRef.value.content).toBe(payload.content);
103
100
 
104
101
  // Update the store using controller.setResponse
105
102
  const newTitle = payload.title + ' updated';
@@ -110,29 +107,31 @@ describe('vue useSuspense()', () => {
110
107
  { ...payload, title: newTitle, content: newContent },
111
108
  );
112
109
 
113
- // Wait for re-render
114
- await waitForNextUpdate();
110
+ // Wait a tick for Vue reactivity to propagate
111
+ await nextTick();
115
112
 
116
- const updatedArticleRef = await result.current;
117
- expect(updatedArticleRef!.value.title).toBe(newTitle);
118
- expect(updatedArticleRef!.value.content).toBe(newContent);
113
+ // The ComputedRef should now have updated values (it's reactive!)
114
+ expect(articleRef.value.title).toBe(newTitle);
115
+ expect(articleRef.value.content).toBe(newContent);
119
116
 
120
117
  cleanup();
121
118
  });
122
119
 
123
120
  it('re-renders when controller.fetch() mutates data', async () => {
124
121
  const { result, controller, waitForNextUpdate, cleanup } =
125
- renderDataComposable(() =>
122
+ await renderDataCompose(() =>
126
123
  useSuspense(CoolerArticleResource.get, { id: payload.id }),
127
124
  );
128
125
 
129
126
  // Wait for initial render
130
127
  await waitForNextUpdate();
131
128
 
129
+ // Await the promise once to get the reactive ComputedRef
130
+ const articleRef = await result;
131
+
132
132
  // Verify initial values
133
- const initialArticleRef = await result.current;
134
- expect(initialArticleRef!.value.title).toBe(payload.title);
135
- expect(initialArticleRef!.value.content).toBe(payload.content);
133
+ expect(articleRef.value.title).toBe(payload.title);
134
+ expect(articleRef.value.content).toBe(payload.content);
136
135
 
137
136
  // Mutate the data using controller.fetch with update endpoint
138
137
  const updatedTitle = payload.title + ' mutated';
@@ -144,18 +143,17 @@ describe('vue useSuspense()', () => {
144
143
  { title: updatedTitle, content: updatedContent },
145
144
  );
146
145
 
147
- // Wait for re-render with new data
148
- await waitForNextUpdate();
146
+ // Wait a tick for Vue reactivity to propagate
147
+ await nextTick();
149
148
 
150
- const updatedArticleRef = await result.current;
151
- expect(updatedArticleRef!.value.title).toBe(updatedTitle);
152
- expect(updatedArticleRef!.value.content).toBe(updatedContent);
149
+ // The ComputedRef should now have updated values (it's reactive!)
150
+ expect(articleRef.value.title).toBe(updatedTitle);
151
+ expect(articleRef.value.content).toBe(updatedContent);
153
152
 
154
153
  cleanup();
155
154
  });
156
155
 
157
156
  it('should re-fetch when props change', async () => {
158
- // Clean up persistent mocks to avoid conflicts
159
157
  nock.cleanAll();
160
158
 
161
159
  const fetchMock1 = jest.fn(() => payload);
@@ -183,22 +181,22 @@ describe('vue useSuspense()', () => {
183
181
  required: true,
184
182
  },
185
183
  },
186
- async setup(props) {
187
- const article = await useSuspense(CoolerArticleResource.get, {
188
- id: props.id,
189
- });
184
+ async setup(props: { id: number }) {
185
+ // Pass the reactive value - useSuspense will track changes via its internal computed
186
+ const article = await useSuspense(CoolerArticleResource.get, props);
190
187
 
191
188
  return () =>
192
189
  h('div', [
193
- h('h3', (article as any).value.title),
194
- h('p', (article as any).value.content),
190
+ h('h3', (article as any).value?.title),
191
+ h('p', (article as any).value?.content),
195
192
  ]);
196
193
  },
197
194
  });
198
195
 
199
- // Use renderDataClient to properly set up the test environment
200
- const { wrapper, cleanup } = renderDataClient(ArticleWithProps, {
201
- initialProps: { id: payload.id },
196
+ // Use mountDataClient to properly set up the test environment
197
+ const props = reactive({ id: payload.id });
198
+ const { wrapper, cleanup } = mountDataClient(ArticleWithProps, {
199
+ props,
202
200
  });
203
201
 
204
202
  // Wait for initial render and verify data
@@ -209,7 +207,8 @@ describe('vue useSuspense()', () => {
209
207
  expect(fetchMock2).toHaveBeenCalledTimes(0);
210
208
 
211
209
  // Change the id prop - this should trigger re-suspense but currently doesn't
212
- await wrapper.setProps({ id: payload2.id });
210
+ props.id = payload2.id;
211
+ await nextTick();
213
212
 
214
213
  // Wait for the new data to render
215
214
  await flushUntil(
@@ -225,6 +224,133 @@ describe('vue useSuspense()', () => {
225
224
  expect(wrapper.find('p').text()).toBe(payload2.content);
226
225
 
227
226
  cleanup();
227
+
228
+ // Restore the original nock interceptors from beforeAll
228
229
  nock.cleanAll();
230
+ nock(/.*/)
231
+ .persist()
232
+ .defaultReplyHeaders({
233
+ 'Access-Control-Allow-Origin': '*',
234
+ 'Access-Control-Allow-Headers': 'Access-Token',
235
+ 'Content-Type': 'application/json',
236
+ })
237
+ .options(/.*/)
238
+ .reply(200)
239
+ .get(`/article-cooler/${payload.id}`)
240
+ .reply(200, payload)
241
+ .get(`/article-cooler/${payload2.id}`)
242
+ .reply(200, payload2)
243
+ .put(`/article-cooler/${payload.id}`)
244
+ .reply(200, (uri, requestBody: any) => ({
245
+ ...payload,
246
+ ...requestBody,
247
+ }));
248
+ });
249
+
250
+ it('should initially resolve, then when args are null should return undefined, then back to resolving', async () => {
251
+ const props = reactive({ id: payload.id as number | null });
252
+ const { result, allSettled, waitForNextUpdate, cleanup } =
253
+ await renderDataCompose(
254
+ (props: { id: number | null }) =>
255
+ useSuspense(
256
+ CoolerArticleResource.get,
257
+ computed(() => (props.id !== null ? { id: props.id } : null)),
258
+ ),
259
+ { props },
260
+ );
261
+
262
+ // Wait for initial render
263
+ await waitForNextUpdate();
264
+
265
+ // Await the promise once to get the reactive ComputedRef
266
+ const articleRef = await result;
267
+
268
+ expect(articleRef).toBeDefined();
269
+
270
+ // Verify initial values
271
+ expect(articleRef.value?.title).toBe(payload.title);
272
+ expect(articleRef.value?.content).toBe(payload.content);
273
+
274
+ // Change to null - the ComputedRef should reactively become undefined
275
+ props.id = null;
276
+ await nextTick();
277
+
278
+ // The same ComputedRef should now have undefined value
279
+ expect(articleRef.value).toBeUndefined();
280
+
281
+ // Change back to valid id - should resolve the new data
282
+ props.id = payload2.id;
283
+ await nextTick();
284
+
285
+ // Wait for the fetch to complete
286
+ await allSettled();
287
+ await nextTick();
288
+
289
+ // The ComputedRef should now have the new article data
290
+ expect(articleRef).toBeDefined();
291
+ expect(articleRef?.value?.title).toBe(payload2.title);
292
+ expect(articleRef.value?.content).toBe(payload2.content);
293
+
294
+ cleanup();
295
+ });
296
+
297
+ it('should initiate second fetch when props change even if first promise never resolves', async () => {
298
+ let fetchInitialCalled = false;
299
+ let fetchFinalCalled = false;
300
+ let resolveInitial: ((value: any) => void) | undefined;
301
+ let resolveFinal: ((value: any) => void) | undefined;
302
+
303
+ // Create custom endpoint with controllable promises
304
+ const ControlledEndpoint = new Endpoint(
305
+ ({ id }: { id: number }) => {
306
+ if (id === payload.id) {
307
+ fetchInitialCalled = true;
308
+ // Initial fetch - manually controlled
309
+ return new Promise(resolve => {
310
+ resolveInitial = resolve;
311
+ });
312
+ } else if (id === payload2.id) {
313
+ fetchFinalCalled = true;
314
+ // Final fetch - manually controlled
315
+ return new Promise(resolve => {
316
+ resolveFinal = resolve;
317
+ });
318
+ }
319
+ throw new Error(`Unexpected id: ${id}`);
320
+ },
321
+ { schema: CoolerArticle, name: 'ControlledEndpoint' },
322
+ );
323
+
324
+ const props = reactive({ id: payload.id });
325
+
326
+ // Start the composable (don't await yet since initial fetch needs manual resolution)
327
+ const setupPromise = renderDataCompose(
328
+ (props: { id: number }) =>
329
+ useSuspense(
330
+ ControlledEndpoint,
331
+ computed(() => ({ id: props.id })),
332
+ ),
333
+ { props },
334
+ );
335
+
336
+ // Wait for initial fetch to be called
337
+ expect(fetchInitialCalled).toBe(true);
338
+
339
+ props.id = payload2.id;
340
+ await nextTick();
341
+
342
+ resolveFinal?.(payload2);
343
+
344
+ // Resolve the initial fetch so renderDataCompose completes
345
+ resolveInitial?.(payload);
346
+
347
+ const { result, cleanup } = await setupPromise;
348
+ const articleRef = await result;
349
+
350
+ // The data should now be from the final fetch (payload2)
351
+ expect(articleRef.value?.title).toBe(payload2.title);
352
+ expect(articleRef.value?.content).toBe(payload2.content);
353
+
354
+ cleanup();
229
355
  });
230
356
  });
@@ -5,4 +5,6 @@ export { default as useLive } from './useLive.js';
5
5
  export { default as useLoading } from './useLoading.js';
6
6
  export { default as useDebounce } from './useDebounce.js';
7
7
  export { default as useFetch } from './useFetch.js';
8
+ export { default as useCache } from './useCache.js';
9
+ export { default as useDLE } from './useDLE.js';
8
10
  export { useController as useController } from '../context.js';
@@ -0,0 +1,122 @@
1
+ import type {
2
+ EndpointInterface,
3
+ DenormalizeNullable,
4
+ Schema,
5
+ FetchFunction,
6
+ ResolveType,
7
+ } from '@data-client/core';
8
+ import { ExpiryStatus } from '@data-client/core';
9
+ import { computed, unref, watch, type ComputedRef } from 'vue';
10
+
11
+ import { useController, injectState } from '../context.js';
12
+ import type {
13
+ MaybeRefsOrGetters,
14
+ MaybeRefsOrGettersNullable,
15
+ } from '../types.js';
16
+
17
+ /**
18
+ * Read an Endpoint's response if it is ready.
19
+ *
20
+ * `useCache` guarantees referential equality globally.
21
+ * @see https://dataclient.io/docs/api/useCache
22
+ */
23
+ export default function useCache<
24
+ E extends Pick<
25
+ EndpointInterface<FetchFunction, Schema | undefined, undefined | boolean>,
26
+ 'key' | 'schema' | 'invalidIfStale'
27
+ >,
28
+ >(
29
+ endpoint: E,
30
+ ...args: MaybeRefsOrGetters<Parameters<E['key']>>
31
+ ): ComputedRef<
32
+ E['schema'] extends undefined | null ?
33
+ E extends (...args: any) => any ?
34
+ ResolveType<E> | undefined
35
+ : any
36
+ : DenormalizeNullable<E['schema']>
37
+ >;
38
+
39
+ export default function useCache<
40
+ E extends Pick<
41
+ EndpointInterface<FetchFunction, Schema | undefined, undefined | boolean>,
42
+ 'key' | 'schema' | 'invalidIfStale'
43
+ >,
44
+ >(
45
+ endpoint: E,
46
+ ...args: MaybeRefsOrGettersNullable<Parameters<E['key']>> | readonly [null]
47
+ ): ComputedRef<
48
+ E['schema'] extends undefined | null ?
49
+ E extends (...args: any) => any ?
50
+ ResolveType<E> | undefined
51
+ : any
52
+ : DenormalizeNullable<E['schema']>
53
+ >;
54
+
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
+ });
122
+ }
@@ -0,0 +1,160 @@
1
+ import type {
2
+ Denormalize,
3
+ DenormalizeNullable,
4
+ ErrorTypes,
5
+ EndpointInterface,
6
+ FetchFunction,
7
+ Schema,
8
+ ResolveType,
9
+ } from '@data-client/core';
10
+ import { ExpiryStatus } from '@data-client/core';
11
+ import { computed, unref, watch, markRaw, type ComputedRef } from 'vue';
12
+
13
+ import { useController, injectState } from '../context.js';
14
+ import type {
15
+ MaybeRefsOrGetters,
16
+ MaybeRefsOrGettersNullable,
17
+ } from '../types.js';
18
+
19
+ /**
20
+ * Use async data with { data, loading, error } (DLE)
21
+ * @see https://dataclient.io/docs/api/useDLE
22
+ */
23
+ export default function useDLE<
24
+ E extends EndpointInterface<
25
+ FetchFunction,
26
+ Schema | undefined,
27
+ undefined | false
28
+ >,
29
+ >(
30
+ endpoint: E,
31
+ ...args: MaybeRefsOrGetters<Parameters<E>>
32
+ ): {
33
+ data: ComputedRef<
34
+ E['schema'] extends undefined | null ? ResolveType<E> | undefined
35
+ : Denormalize<E['schema']> | DenormalizeNullable<E['schema']>
36
+ >;
37
+ loading: ComputedRef<boolean>;
38
+ error: ComputedRef<ErrorTypes | undefined>;
39
+ };
40
+
41
+ export default function useDLE<
42
+ E extends EndpointInterface<
43
+ FetchFunction,
44
+ Schema | undefined,
45
+ undefined | false
46
+ >,
47
+ >(
48
+ endpoint: E,
49
+ ...args: MaybeRefsOrGettersNullable<Parameters<E>> | readonly [null]
50
+ ): {
51
+ data: ComputedRef<
52
+ E['schema'] extends undefined | null ? undefined
53
+ : DenormalizeNullable<E['schema']>
54
+ >;
55
+ loading: ComputedRef<boolean>;
56
+ error: ComputedRef<ErrorTypes | undefined>;
57
+ };
58
+
59
+ export default function useDLE(endpoint: any, ...args: any[]): any {
60
+ const stateRef = injectState();
61
+ const controller = useController();
62
+
63
+ // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger updates.
64
+ const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
65
+
66
+ // Compute a key that changes when args change (including reactive props)
67
+ const argsKey = computed(() =>
68
+ resolvedArgs.value[0] !== null ? endpoint.key(...resolvedArgs.value) : '',
69
+ );
70
+
71
+ // Compute response meta reactively so we can respond to store updates
72
+ const responseMeta = computed(() => {
73
+ return controller.getResponseMeta(
74
+ endpoint,
75
+ ...resolvedArgs.value,
76
+ stateRef.value,
77
+ );
78
+ });
79
+
80
+ // If we are hard invalid we must fetch regardless of triggering or staleness
81
+ const forceFetch = computed(
82
+ () => responseMeta.value.expiryStatus === ExpiryStatus.Invalid,
83
+ );
84
+
85
+ /*********** This block is to ensure results are only filled when they would not suspend **************/
86
+ // This computation reflects the behavior of useSuspense/useFetch
87
+ // It only changes the value when expiry or params change.
88
+ // This way, random unrelated re-renders don't cause the concept of expiry
89
+ // to change
90
+ const expired = computed(() => {
91
+ return !!(
92
+ (Date.now() > responseMeta.value.expiresAt || forceFetch.value) &&
93
+ argsKey.value
94
+ );
95
+ });
96
+
97
+ // fully "valid" data will not suspend/loading even if it is not fresh
98
+ const loading = computed(() => {
99
+ return !!(
100
+ responseMeta.value.expiryStatus !== ExpiryStatus.Valid && expired.value
101
+ );
102
+ });
103
+ /****************************************************************************************************/
104
+
105
+ // Trigger fetch when necessary
106
+ watch(
107
+ () => {
108
+ const m = responseMeta.value;
109
+ return [
110
+ m.expiresAt,
111
+ m.expiryStatus,
112
+ stateRef.value.lastReset,
113
+ argsKey.value,
114
+ ];
115
+ },
116
+ async () => {
117
+ const currentKey = argsKey.value;
118
+ if (!currentKey) return;
119
+ const meta = responseMeta.value;
120
+ const force = forceFetch.value;
121
+ if (Date.now() <= meta.expiresAt && !force) return;
122
+ await controller.fetch(endpoint, ...resolvedArgs.value).catch(() => {});
123
+ },
124
+ { immediate: true },
125
+ );
126
+
127
+ // Maintain GC refcounts on data mount/changes
128
+ watch(
129
+ () => responseMeta.value.data,
130
+ (_newVal, _oldVal, onCleanup) => {
131
+ const decrement = responseMeta.value.countRef();
132
+ onCleanup(() => decrement());
133
+ },
134
+ { immediate: true },
135
+ );
136
+
137
+ const data = computed(() => {
138
+ // if useSuspense() would suspend, don't include entities from cache
139
+ if (loading.value) {
140
+ if (!endpoint.schema) return undefined;
141
+ // TODO: use getResponse() once it just returns data
142
+ return controller.getResponseMeta(endpoint, ...resolvedArgs.value, {
143
+ ...stateRef.value,
144
+ entities: {},
145
+ }).data as any;
146
+ }
147
+ return responseMeta.value.data;
148
+ });
149
+
150
+ const error = computed(() => {
151
+ return controller.getError(endpoint, ...resolvedArgs.value, stateRef.value);
152
+ });
153
+
154
+ // Use markRaw to prevent Vue from auto-unwrapping the computed refs
155
+ return markRaw({
156
+ data,
157
+ loading,
158
+ error,
159
+ });
160
+ }