@data-client/vue 0.0.5 → 0.1.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 (74) hide show
  1. package/README.md +10 -4
  2. package/dist/index.js +114 -34
  3. package/dist/index.umd.min.js +1 -1
  4. package/lib/consumers/useFetch.js +12 -8
  5. package/lib/consumers/useSuspense.js +38 -13
  6. package/lib/context.d.ts.map +1 -1
  7. package/lib/context.js +3 -1
  8. package/lib/providers/DataClientPlugin.d.ts +22 -0
  9. package/lib/providers/DataClientPlugin.d.ts.map +1 -0
  10. package/lib/providers/DataClientPlugin.js +40 -0
  11. package/lib/providers/{provideDataClient.d.ts → createDataClient.d.ts} +10 -6
  12. package/lib/providers/createDataClient.d.ts.map +1 -0
  13. package/lib/providers/createDataClient.js +103 -0
  14. package/lib/providers/index.d.ts +2 -1
  15. package/lib/providers/index.d.ts.map +1 -1
  16. package/lib/providers/index.js +3 -2
  17. package/lib/test/MockController.d.ts +8 -0
  18. package/lib/test/MockController.d.ts.map +1 -0
  19. package/lib/test/MockController.js +125 -0
  20. package/lib/test/collapseFixture.d.ts +6 -0
  21. package/lib/test/collapseFixture.d.ts.map +1 -0
  22. package/lib/test/collapseFixture.js +19 -0
  23. package/lib/test/createFixtureMap.d.ts +3 -0
  24. package/lib/test/createFixtureMap.d.ts.map +1 -0
  25. package/lib/test/createFixtureMap.js +23 -0
  26. package/lib/test/fixtureTypes.d.ts +99 -0
  27. package/lib/test/fixtureTypes.d.ts.map +1 -0
  28. package/lib/test/fixtureTypes.js +2 -0
  29. package/lib/test/index.d.ts +8 -0
  30. package/lib/test/index.d.ts.map +1 -0
  31. package/lib/test/index.js +7 -0
  32. package/lib/test/mockState.d.ts +4 -0
  33. package/lib/test/mockState.d.ts.map +1 -0
  34. package/lib/test/mockState.js +44 -0
  35. package/lib/test/renderDataClient.d.ts +40 -0
  36. package/lib/test/renderDataClient.d.ts.map +1 -0
  37. package/lib/test/renderDataClient.js +264 -0
  38. package/package.json +13 -6
  39. package/src/__tests__/__snapshots__/useQuery.web.ts.snap +126 -0
  40. package/src/__tests__/__snapshots__/useSubscription.web.ts.snap +7 -0
  41. package/src/__tests__/integration-garbage-collection.web.ts +155 -0
  42. package/src/__tests__/useFetch.web.ts +192 -51
  43. package/src/__tests__/useLive.web.ts +66 -34
  44. package/src/__tests__/useQuery.web.ts +263 -109
  45. package/src/__tests__/useSubscription.web.ts +16 -3
  46. package/src/__tests__/useSuspense.web.ts +141 -70
  47. package/src/consumers/useFetch.ts +16 -9
  48. package/src/consumers/useSuspense.ts +37 -15
  49. package/src/context.ts +2 -0
  50. package/src/providers/DataClientPlugin.ts +39 -0
  51. package/src/providers/__tests__/DataClientPlugin.test.ts +387 -0
  52. package/src/providers/{provideDataClient.ts → createDataClient.ts} +33 -24
  53. package/src/providers/index.ts +2 -1
  54. package/src/test/MockController.ts +151 -0
  55. package/src/test/README.md +245 -0
  56. package/src/test/collapseFixture.ts +21 -0
  57. package/src/test/createFixtureMap.ts +26 -0
  58. package/src/test/fixtureTypes.ts +121 -0
  59. package/src/test/index.ts +23 -0
  60. package/src/test/mockState.ts +57 -0
  61. package/src/test/renderDataClient.ts +316 -0
  62. package/ts3.4/providers/DataClientPlugin.d.ts +22 -0
  63. package/ts3.4/providers/createDataClient.d.ts +25 -0
  64. package/ts3.4/providers/index.d.ts +2 -1
  65. package/ts3.4/test/MockController.d.ts +8 -0
  66. package/ts3.4/test/collapseFixture.d.ts +6 -0
  67. package/ts3.4/test/createFixtureMap.d.ts +6 -0
  68. package/ts3.4/test/fixtureTypes.d.ts +99 -0
  69. package/ts3.4/test/index.d.ts +8 -0
  70. package/ts3.4/test/mockState.d.ts +4 -0
  71. package/ts3.4/test/renderDataClient.d.ts +40 -0
  72. package/lib/providers/provideDataClient.d.ts.map +0 -1
  73. package/lib/providers/provideDataClient.js +0 -94
  74. package/ts3.4/providers/provideDataClient.d.ts +0 -21
@@ -1,9 +1,13 @@
1
- import { mount } from '@vue/test-utils';
2
1
  import nock from 'nock';
3
- import { defineComponent, h, nextTick, Suspense } from 'vue';
2
+ import { defineComponent, h, nextTick } from 'vue';
4
3
 
5
- // Reuse the same endpoints/fixtures used by the React tests
6
4
  import { CoolerArticleResource } from '../../../../__tests__/new';
5
+ import useSuspense from '../consumers/useSuspense';
6
+ import {
7
+ renderDataComposable,
8
+ renderDataClient,
9
+ } from '../test/renderDataClient';
10
+
7
11
  // Minimal shared fixture (copied from React test fixtures)
8
12
  const payload = {
9
13
  id: 5,
@@ -11,8 +15,13 @@ const payload = {
11
15
  content: 'whatever',
12
16
  tags: ['a', 'best', 'react'],
13
17
  };
14
- import useSuspense from '../consumers/useSuspense';
15
- import { provideDataClient } from '../providers/provideDataClient';
18
+
19
+ const payload2 = {
20
+ id: 6,
21
+ title: 'next',
22
+ content: 'my best content yet',
23
+ tags: ['b'],
24
+ };
16
25
 
17
26
  describe('vue useSuspense()', () => {
18
27
  async function flushUntil(
@@ -40,6 +49,8 @@ describe('vue useSuspense()', () => {
40
49
  .reply(200)
41
50
  .get(`/article-cooler/${payload.id}`)
42
51
  .reply(200, payload)
52
+ .get(`/article-cooler/${payload2.id}`)
53
+ .reply(200, payload2)
43
54
  .put(`/article-cooler/${payload.id}`)
44
55
  .reply(200, (uri, requestBody: any) => ({
45
56
  ...payload,
@@ -51,109 +62,169 @@ describe('vue useSuspense()', () => {
51
62
  nock.cleanAll();
52
63
  });
53
64
 
54
- const ArticleComp = defineComponent({
55
- name: 'ArticleComp',
56
- async setup() {
57
- const article = await useSuspense(CoolerArticleResource.get, {
58
- id: payload.id,
59
- });
60
- return () =>
61
- h('div', [
62
- h('h3', (article as any).value.title),
63
- h('p', (article as any).value.content),
64
- ]);
65
- },
66
- });
67
-
68
- const ProvideWrapper = defineComponent({
69
- name: 'ProvideWrapper',
70
- setup(_props, { slots, expose }) {
71
- const { controller } = provideDataClient();
72
- expose({ controller });
73
- return () =>
74
- h(
75
- Suspense,
76
- {},
77
- {
78
- default: () => (slots.default ? slots.default() : h(ArticleComp)),
79
- fallback: () => h('div', { class: 'fallback' }, 'Loading'),
80
- },
81
- );
82
- },
83
- });
65
+ // No need for ProvideWrapper anymore since Suspense is integrated into renderDataClient
84
66
 
85
67
  it('suspends on empty store, then renders after fetch resolves', async () => {
86
- const wrapper = mount(ProvideWrapper, {
87
- slots: { default: () => h(ArticleComp) },
88
- });
68
+ const { result, waitForNextUpdate, cleanup } = renderDataComposable(() =>
69
+ useSuspense(CoolerArticleResource.get, { id: payload.id }),
70
+ );
89
71
 
90
- // Initially should render fallback while Suspense is pending
91
- expect(wrapper.find('.fallback').exists()).toBe(true);
72
+ // Initially should be undefined while suspended (React-like interface)
73
+ expect(result.current).toBeUndefined();
92
74
 
93
- // Flush pending promises/ticks until content renders
94
- await flushUntil(wrapper, () => wrapper.find('h3').exists());
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);
81
+
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);
95
86
 
96
- const title = wrapper.find('h3');
97
- const content = wrapper.find('p');
98
- expect(title.exists()).toBe(true);
99
- expect(content.exists()).toBe(true);
100
- expect(title.text()).toBe(payload.title);
101
- expect(content.text()).toBe(payload.content);
87
+ cleanup();
102
88
  });
103
89
 
104
90
  it('re-renders when controller.setResponse() updates data', async () => {
105
- const wrapper = mount(ProvideWrapper, {
106
- slots: { default: () => h(ArticleComp) },
107
- });
91
+ const { result, controller, waitForNextUpdate, cleanup } =
92
+ renderDataComposable(() =>
93
+ useSuspense(CoolerArticleResource.get, { id: payload.id }),
94
+ );
95
+
108
96
  // Wait for initial render
109
- await flushUntil(wrapper, () => wrapper.find('h3').exists());
97
+ await waitForNextUpdate();
110
98
 
111
99
  // Verify initial values
112
- expect(wrapper.find('h3').text()).toBe(payload.title);
113
- expect(wrapper.find('p').text()).toBe(payload.content);
100
+ const initialArticleRef = await result.current;
101
+ expect(initialArticleRef!.value.title).toBe(payload.title);
102
+ expect(initialArticleRef!.value.content).toBe(payload.content);
114
103
 
115
104
  // Update the store using controller.setResponse
116
- const exposed: any = wrapper.vm as any;
117
105
  const newTitle = payload.title + ' updated';
118
106
  const newContent = (payload as any).content + ' v2';
119
- exposed.controller.setResponse(
107
+ controller.setResponse(
120
108
  CoolerArticleResource.get,
121
109
  { id: payload.id },
122
110
  { ...payload, title: newTitle, content: newContent },
123
111
  );
124
112
 
125
- await flushUntil(wrapper, () => wrapper.find('h3').text() === newTitle);
113
+ // Wait for re-render
114
+ await waitForNextUpdate();
115
+
116
+ const updatedArticleRef = await result.current;
117
+ expect(updatedArticleRef!.value.title).toBe(newTitle);
118
+ expect(updatedArticleRef!.value.content).toBe(newContent);
126
119
 
127
- expect(wrapper.find('h3').text()).toBe(newTitle);
128
- expect(wrapper.find('p').text()).toBe(newContent);
120
+ cleanup();
129
121
  });
130
122
 
131
123
  it('re-renders when controller.fetch() mutates data', async () => {
132
- const wrapper = mount(ProvideWrapper, {
133
- slots: { default: () => h(ArticleComp) },
134
- });
124
+ const { result, controller, waitForNextUpdate, cleanup } =
125
+ renderDataComposable(() =>
126
+ useSuspense(CoolerArticleResource.get, { id: payload.id }),
127
+ );
128
+
135
129
  // Wait for initial render
136
- await flushUntil(wrapper, () => wrapper.find('h3').exists());
130
+ await waitForNextUpdate();
137
131
 
138
132
  // Verify initial values
139
- expect(wrapper.find('h3').text()).toBe(payload.title);
140
- expect(wrapper.find('p').text()).toBe(payload.content);
133
+ const initialArticleRef = await result.current;
134
+ expect(initialArticleRef!.value.title).toBe(payload.title);
135
+ expect(initialArticleRef!.value.content).toBe(payload.content);
141
136
 
142
137
  // Mutate the data using controller.fetch with update endpoint
143
- const exposed: any = wrapper.vm as any;
144
138
  const updatedTitle = payload.title + ' mutated';
145
139
  const updatedContent = payload.content + ' mutated';
146
140
 
147
- await exposed.controller.fetch(
141
+ await controller.fetch(
148
142
  CoolerArticleResource.update,
149
143
  { id: payload.id },
150
144
  { title: updatedTitle, content: updatedContent },
151
145
  );
152
146
 
153
147
  // Wait for re-render with new data
154
- await flushUntil(wrapper, () => wrapper.find('h3').text() === updatedTitle);
148
+ await waitForNextUpdate();
149
+
150
+ const updatedArticleRef = await result.current;
151
+ expect(updatedArticleRef!.value.title).toBe(updatedTitle);
152
+ expect(updatedArticleRef!.value.content).toBe(updatedContent);
155
153
 
156
- expect(wrapper.find('h3').text()).toBe(updatedTitle);
157
- expect(wrapper.find('p').text()).toBe(updatedContent);
154
+ cleanup();
155
+ });
156
+
157
+ it('should re-fetch when props change', async () => {
158
+ // Clean up persistent mocks to avoid conflicts
159
+ nock.cleanAll();
160
+
161
+ const fetchMock1 = jest.fn(() => payload);
162
+ const fetchMock2 = jest.fn(() => payload2);
163
+
164
+ nock(/.*/)
165
+ .persist()
166
+ .defaultReplyHeaders({
167
+ 'Access-Control-Allow-Origin': '*',
168
+ 'Access-Control-Allow-Headers': 'Access-Token',
169
+ 'Content-Type': 'application/json',
170
+ })
171
+ .options(/.*/)
172
+ .reply(200)
173
+ .get(`/article-cooler/${payload.id}`)
174
+ .reply(200, fetchMock1)
175
+ .get(`/article-cooler/${payload2.id}`)
176
+ .reply(200, fetchMock2);
177
+
178
+ const ArticleWithProps = defineComponent({
179
+ name: 'ArticleWithProps',
180
+ props: {
181
+ id: {
182
+ type: Number,
183
+ required: true,
184
+ },
185
+ },
186
+ async setup(props) {
187
+ const article = await useSuspense(CoolerArticleResource.get, {
188
+ id: props.id,
189
+ });
190
+
191
+ return () =>
192
+ h('div', [
193
+ h('h3', (article as any).value.title),
194
+ h('p', (article as any).value.content),
195
+ ]);
196
+ },
197
+ });
198
+
199
+ // Use renderDataClient to properly set up the test environment
200
+ const { wrapper, cleanup } = renderDataClient(ArticleWithProps, {
201
+ initialProps: { id: payload.id },
202
+ });
203
+
204
+ // Wait for initial render and verify data
205
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
206
+ expect(wrapper.find('h3').text()).toBe(payload.title);
207
+ expect(wrapper.find('p').text()).toBe(payload.content);
208
+ expect(fetchMock1).toHaveBeenCalledTimes(1);
209
+ expect(fetchMock2).toHaveBeenCalledTimes(0);
210
+
211
+ // Change the id prop - this should trigger re-suspense but currently doesn't
212
+ await wrapper.setProps({ id: payload2.id });
213
+
214
+ // Wait for the new data to render
215
+ await flushUntil(
216
+ wrapper,
217
+ () =>
218
+ wrapper.find('h3').exists() &&
219
+ wrapper.find('h3').text() === payload2.title,
220
+ );
221
+
222
+ expect(fetchMock1).toHaveBeenCalledTimes(1);
223
+ expect(fetchMock2).toHaveBeenCalledTimes(1);
224
+ expect(wrapper.find('h3').text()).toBe(payload2.title);
225
+ expect(wrapper.find('p').text()).toBe(payload2.content);
226
+
227
+ cleanup();
228
+ nock.cleanAll();
158
229
  });
159
230
  });
@@ -6,7 +6,7 @@ import type {
6
6
  FetchFunction,
7
7
  DenormalizeNullable,
8
8
  } from '@data-client/core';
9
- import { computed, watch } from 'vue';
9
+ import { computed, watch, ref } from 'vue';
10
10
 
11
11
  import { useController, injectState } from '../context.js';
12
12
 
@@ -44,22 +44,27 @@ export default function useFetch(endpoint: any, ...args: any[]): any {
44
44
  const stateRef = injectState();
45
45
  const controller = useController();
46
46
 
47
- const key: string = args[0] !== null ? endpoint.key(...args) : '';
47
+ // Compute a key that changes when args change (including reactive props)
48
+ const argsKey = computed(() =>
49
+ args[0] !== null ? endpoint.key(...args) : '',
50
+ );
48
51
 
49
52
  // Compute response meta reactively so we can respond to store updates
50
- const responseMeta = computed(() =>
51
- key ? controller.getResponseMeta(endpoint, ...args, stateRef.value) : null,
52
- );
53
+ const responseMeta = computed(() => {
54
+ return argsKey.value ?
55
+ controller.getResponseMeta(endpoint, ...args, stateRef.value)
56
+ : null;
57
+ });
53
58
 
54
- let lastPromise: Promise<any> | undefined = undefined;
59
+ const lastPromise = ref<Promise<any> | undefined>(undefined);
55
60
 
56
61
  const maybeFetch = () => {
57
- if (!key) return;
62
+ if (args[0] === null) return;
58
63
  const meta = responseMeta.value;
59
64
  if (!meta) return;
60
65
  const forceFetch = meta.expiryStatus === ExpiryStatus.Invalid;
61
66
  if (Date.now() <= meta.expiresAt && !forceFetch) return;
62
- lastPromise = controller.fetch(endpoint, ...(args as any));
67
+ lastPromise.value = controller.fetch(endpoint, ...(args as any));
63
68
  };
64
69
 
65
70
  // Trigger on initial call
@@ -69,7 +74,9 @@ export default function useFetch(endpoint: any, ...args: any[]): any {
69
74
  watch(
70
75
  () => {
71
76
  const m = responseMeta.value;
72
- return m ? [m.expiresAt, m.expiryStatus, stateRef.value.lastReset] : key;
77
+ return m ?
78
+ [m.expiresAt, m.expiryStatus, stateRef.value.lastReset, argsKey.value]
79
+ : [argsKey.value];
73
80
  },
74
81
  () => {
75
82
  maybeFetch();
@@ -60,32 +60,54 @@ export default async function useSuspense(
60
60
  const stateRef = injectState();
61
61
  const controller = useController();
62
62
 
63
- const key = args[0] !== null ? endpoint.key(...args) : '';
64
- const responseMeta = computed(() =>
65
- controller.getResponseMeta(endpoint, ...args, stateRef.value),
63
+ // Compute a key that changes when args change (including reactive props)
64
+ const argsKey = computed(() =>
65
+ args[0] !== null ? endpoint.key(...args) : '',
66
66
  );
67
67
 
68
- // If invalid or expired, perform fetch and await it to integrate with Vue Suspense
69
- const isInvalid =
70
- responseMeta.value.expiryStatus === ExpiryStatus.Invalid ||
71
- Date.now() > responseMeta.value.expiresAt;
72
- if (key && isInvalid) {
68
+ // Compute response meta reactively so we can respond to store updates
69
+ const responseMeta = computed(() => {
70
+ return argsKey.value ?
71
+ controller.getResponseMeta(endpoint, ...args, stateRef.value)
72
+ : null;
73
+ });
74
+
75
+ const maybeFetch = async () => {
76
+ const currentKey = argsKey.value;
77
+ if (!currentKey) return;
78
+ const meta = responseMeta.value;
79
+ if (!meta) return;
80
+ const forceFetch = meta.expiryStatus === ExpiryStatus.Invalid;
81
+ if (Date.now() <= meta.expiresAt && !forceFetch) return;
73
82
  await controller.fetch(endpoint, ...(args as any));
74
- }
83
+ };
84
+
85
+ // Trigger on initial call
86
+ await maybeFetch();
75
87
 
76
- const error = controller.getError(endpoint, ...args, stateRef.value);
77
- if (error) throw error;
88
+ // Watch for changes to key, expiry, or store state that require refetch
89
+ watch(
90
+ () => {
91
+ const m = responseMeta.value;
92
+ return m ?
93
+ [m.expiresAt, m.expiryStatus, stateRef.value.lastReset, argsKey.value]
94
+ : [argsKey.value];
95
+ },
96
+ () => {
97
+ return maybeFetch();
98
+ },
99
+ );
78
100
 
79
101
  // Maintain GC refcounts on data mount/changes
80
102
  watch(
81
- () => responseMeta.value.data,
103
+ () => responseMeta.value?.data,
82
104
  (_newVal, _oldVal, onCleanup) => {
83
- const decrement = responseMeta.value.countRef();
84
- onCleanup(() => decrement());
105
+ const decrement = responseMeta.value?.countRef();
106
+ onCleanup(() => decrement?.());
85
107
  },
86
108
  { immediate: true },
87
109
  );
88
110
 
89
111
  // Return readonly computed ref - Vue automatically unwraps in templates and reactive contexts
90
- return readonly(computed(() => responseMeta.value.data));
112
+ return readonly(computed(() => responseMeta.value?.data));
91
113
  }
package/src/context.ts CHANGED
@@ -16,6 +16,7 @@ export const FallbackStateRef: ShallowRef<State<unknown>> =
16
16
  export function useController(): Controller {
17
17
  const ctrl = inject(ControllerKey, null);
18
18
  if (!ctrl) {
19
+ /* istanbul ignore else */
19
20
  if (process.env.NODE_ENV !== 'production') {
20
21
  console.error(
21
22
  'It appears you are trying to use Reactive Data Client (Vue) without a provider.\n' +
@@ -30,6 +31,7 @@ export function useController(): Controller {
30
31
  export function injectState(): ShallowRef<State<unknown>> {
31
32
  const state = inject(StateKey, null);
32
33
  if (!state) {
34
+ /* istanbul ignore else */
33
35
  if (process.env.NODE_ENV !== 'production') {
34
36
  console.error(
35
37
  'It appears you are trying to use Reactive Data Client (Vue) without a provider.\n' +
@@ -0,0 +1,39 @@
1
+ import type { App } from 'vue';
2
+
3
+ import { createDataClient, type ProvideOptions } from './createDataClient.js';
4
+
5
+ /**
6
+ * Vue 3 Plugin for Reactive Data Client
7
+ *
8
+ * Usage:
9
+ * ```ts
10
+ * import { createApp } from 'vue';
11
+ * import { DataClientPlugin } from '@data-client/vue';
12
+ *
13
+ * const app = createApp(App);
14
+ * app.use(DataClientPlugin, {
15
+ * managers: getDefaultManagers(),
16
+ * initialState: customInitialState,
17
+ * });
18
+ * app.mount('#app');
19
+ * ```
20
+ */
21
+ export const DataClientPlugin = {
22
+ install(app: App, options: ProvideOptions = {}) {
23
+ const provider = createDataClient({ ...options, app });
24
+
25
+ // Handle lifecycle in plugin mode
26
+ if (app.mixin) {
27
+ app.mixin({
28
+ beforeMount() {
29
+ provider.start();
30
+ },
31
+ beforeUnmount() {
32
+ provider.stop();
33
+ },
34
+ });
35
+ }
36
+
37
+ return provider;
38
+ },
39
+ };