@data-client/vue 0.0.1

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 (72) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +315 -0
  3. package/data_client_logo_and_text.svg +64 -0
  4. package/dist/index.js +290 -0
  5. package/dist/index.umd.min.js +1 -0
  6. package/dist/package.json +1 -0
  7. package/lib/components/DataProvider.d.ts +11 -0
  8. package/lib/components/DataProvider.d.ts.map +1 -0
  9. package/lib/components/DataProvider.js +18 -0
  10. package/lib/consumers/index.d.ts +5 -0
  11. package/lib/consumers/index.d.ts.map +1 -0
  12. package/lib/consumers/index.js +5 -0
  13. package/lib/consumers/useInjects.d.ts +5 -0
  14. package/lib/consumers/useInjects.d.ts.map +1 -0
  15. package/lib/consumers/useInjects.js +8 -0
  16. package/lib/consumers/useQuery.d.ts +12 -0
  17. package/lib/consumers/useQuery.d.ts.map +1 -0
  18. package/lib/consumers/useQuery.js +29 -0
  19. package/lib/consumers/useSubscription.d.ts +8 -0
  20. package/lib/consumers/useSubscription.d.ts.map +1 -0
  21. package/lib/consumers/useSubscription.js +31 -0
  22. package/lib/consumers/useSuspense.d.ts +5 -0
  23. package/lib/consumers/useSuspense.d.ts.map +1 -0
  24. package/lib/consumers/useSuspense.js +29 -0
  25. package/lib/context.d.ts +10 -0
  26. package/lib/context.d.ts.map +1 -0
  27. package/lib/context.js +28 -0
  28. package/lib/index.d.ts +6 -0
  29. package/lib/index.d.ts.map +1 -0
  30. package/lib/index.js +8 -0
  31. package/lib/managers/index.d.ts +2 -0
  32. package/lib/managers/index.d.ts.map +1 -0
  33. package/lib/managers/index.js +2 -0
  34. package/lib/providers/getDefaultManagers.d.ts +14 -0
  35. package/lib/providers/getDefaultManagers.d.ts.map +1 -0
  36. package/lib/providers/getDefaultManagers.js +51 -0
  37. package/lib/providers/index.d.ts +3 -0
  38. package/lib/providers/index.d.ts.map +1 -0
  39. package/lib/providers/index.js +3 -0
  40. package/lib/providers/provideDataClient.d.ts +21 -0
  41. package/lib/providers/provideDataClient.d.ts.map +1 -0
  42. package/lib/providers/provideDataClient.js +94 -0
  43. package/package.json +143 -0
  44. package/src/__tests__/index.test.ts +10 -0
  45. package/src/__tests__/useQuery.web.ts +207 -0
  46. package/src/__tests__/useSubscription.web.ts +151 -0
  47. package/src/__tests__/useSuspense.web.ts +159 -0
  48. package/src/components/DataProvider.ts +26 -0
  49. package/src/consumers/index.ts +7 -0
  50. package/src/consumers/useInjects.ts +12 -0
  51. package/src/consumers/useQuery.ts +43 -0
  52. package/src/consumers/useSubscription.ts +44 -0
  53. package/src/consumers/useSuspense.ts +91 -0
  54. package/src/context.ts +42 -0
  55. package/src/index.ts +48 -0
  56. package/src/managers/index.ts +8 -0
  57. package/src/providers/getDefaultManagers.ts +80 -0
  58. package/src/providers/index.ts +2 -0
  59. package/src/providers/provideDataClient.ts +126 -0
  60. package/ts3.4/components/DataProvider.d.ts +11 -0
  61. package/ts3.4/consumers/index.d.ts +5 -0
  62. package/ts3.4/consumers/useInjects.d.ts +5 -0
  63. package/ts3.4/consumers/useQuery.d.ts +12 -0
  64. package/ts3.4/consumers/useSubscription.d.ts +12 -0
  65. package/ts3.4/consumers/useSuspense.d.ts +11 -0
  66. package/ts3.4/context.d.ts +10 -0
  67. package/ts3.4/index.d.ts +6 -0
  68. package/ts3.4/managers/index.d.ts +2 -0
  69. package/ts3.4/providers/getDefaultManagers.d.ts +14 -0
  70. package/ts3.4/providers/index.d.ts +3 -0
  71. package/ts3.4/providers/provideDataClient.d.ts +21 -0
  72. package/typescript.svg +8 -0
@@ -0,0 +1,207 @@
1
+ import { schema } from '@data-client/endpoint';
2
+ import { resource } from '@data-client/rest';
3
+ import { mount } from '@vue/test-utils';
4
+ import { defineComponent, h, nextTick } from 'vue';
5
+
6
+ import {
7
+ ArticleWithSlug,
8
+ ArticleSlugResource,
9
+ ArticleResource,
10
+ IDEntity,
11
+ } from '../../../../__tests__/new';
12
+ import useQuery from '../consumers/useQuery';
13
+ import { provideDataClient } from '../providers/provideDataClient';
14
+
15
+ // Inline fixtures (duplicated from React tests to avoid cross-project imports)
16
+ const payloadSlug = {
17
+ id: 5,
18
+ title: 'hi ho',
19
+ slug: 'hi-ho',
20
+ content: 'whatever',
21
+ tags: ['a', 'best', 'react'],
22
+ };
23
+ const nested = [
24
+ {
25
+ id: 5,
26
+ title: 'hi ho',
27
+ content: 'whatever',
28
+ tags: ['a', 'best', 'react'],
29
+ author: {
30
+ id: 23,
31
+ username: 'bob',
32
+ },
33
+ },
34
+ {
35
+ id: 3,
36
+ title: 'the next time',
37
+ content: 'whatever',
38
+ author: {
39
+ id: 23,
40
+ username: 'charles',
41
+ email: 'bob@bob.com',
42
+ },
43
+ },
44
+ ];
45
+
46
+ describe('vue useQuery()', () => {
47
+ async function flush() {
48
+ await Promise.resolve();
49
+ await nextTick();
50
+ }
51
+
52
+ const ProvideWrapper = defineComponent({
53
+ name: 'ProvideWrapper',
54
+ setup(_props, { slots, expose }) {
55
+ const { controller } = provideDataClient();
56
+ expose({ controller });
57
+ return () => (slots.default ? slots.default() : null);
58
+ },
59
+ });
60
+
61
+ it('returns undefined with empty state', async () => {
62
+ const Inner = defineComponent({
63
+ setup() {
64
+ const val = useQuery(ArticleWithSlug, { id: payloadSlug.id });
65
+ return () => h('div', (val.value as any)?.title || '');
66
+ },
67
+ });
68
+
69
+ const wrapper = mount(ProvideWrapper, {
70
+ slots: { default: () => h(Inner) },
71
+ });
72
+ await flush();
73
+ expect(wrapper.text()).toBe('');
74
+ });
75
+
76
+ it('finds Entity by pk/slug after setResponse', async () => {
77
+ const Inner = defineComponent({
78
+ setup() {
79
+ const byId = useQuery(ArticleWithSlug, { id: payloadSlug.id });
80
+ const bySlug = useQuery(ArticleWithSlug, { slug: payloadSlug.slug });
81
+ return () =>
82
+ h(
83
+ 'div',
84
+ `${(byId.value as any)?.title || ''}|${
85
+ (bySlug.value as any)?.title || ''
86
+ }`,
87
+ );
88
+ },
89
+ });
90
+
91
+ const wrapper = mount(ProvideWrapper, {
92
+ slots: { default: () => h(Inner) },
93
+ });
94
+ const { controller }: any = wrapper.vm as any;
95
+
96
+ // seed data via controller
97
+ controller.setResponse(
98
+ ArticleSlugResource.get,
99
+ { id: payloadSlug.id },
100
+ payloadSlug,
101
+ );
102
+ await flush();
103
+
104
+ expect(wrapper.text()).toContain(payloadSlug.title);
105
+ });
106
+
107
+ it('selects Collections and updates when pushed', async () => {
108
+ const ListComp = defineComponent({
109
+ setup() {
110
+ const list = useQuery(ArticleResource.getList.schema);
111
+ return () =>
112
+ h('div', (list.value || []).map((a: any) => a.id).join(','));
113
+ },
114
+ });
115
+
116
+ const wrapper = mount(ProvideWrapper, {
117
+ slots: { default: () => h(ListComp) },
118
+ });
119
+ const { controller }: any = wrapper.vm as any;
120
+
121
+ controller.setResponse(ArticleResource.getList, {}, nested);
122
+ await flush();
123
+ expect(wrapper.text().split(',').filter(Boolean).length).toBe(
124
+ nested.length,
125
+ );
126
+
127
+ // Simulate push by setting new list value
128
+ const appended = nested.concat({
129
+ id: 50,
130
+ title: 'new',
131
+ content: 'x',
132
+ } as any);
133
+ controller.setResponse(ArticleResource.getList, {}, appended);
134
+ await flush();
135
+ expect(wrapper.text().split(',').filter(Boolean).length).toBe(
136
+ nested.length + 1,
137
+ );
138
+ });
139
+
140
+ it('retrieves a nested collection (Collection of Array)', async () => {
141
+ class Todo extends IDEntity {
142
+ userId = 0;
143
+ title = '';
144
+ completed = false;
145
+ static key = 'Todo';
146
+ }
147
+
148
+ class User extends IDEntity {
149
+ name = '';
150
+ username = '';
151
+ email = '';
152
+ todos: Todo[] = [];
153
+ static key = 'User';
154
+ static schema = {
155
+ todos: new schema.Collection(new schema.Array(Todo), {
156
+ nestKey: (parent: any) => ({ userId: parent.id }),
157
+ }),
158
+ };
159
+ }
160
+
161
+ const userTodos = new schema.Collection(new schema.Array(Todo), {
162
+ argsKey: ({ userId }: { userId: string }) => ({ userId }),
163
+ });
164
+
165
+ const UserResource = resource({ schema: User, path: '/users/:id' });
166
+
167
+ const Inner = defineComponent({
168
+ setup() {
169
+ const todos = useQuery(userTodos, { userId: '1' });
170
+ return () => h('div', (todos.value || []).length.toString());
171
+ },
172
+ });
173
+
174
+ const wrapper = mount(ProvideWrapper, {
175
+ slots: { default: () => h(Inner) },
176
+ });
177
+ const { controller }: any = wrapper.vm as any;
178
+
179
+ controller.setResponse(
180
+ UserResource.get,
181
+ { id: '1' },
182
+ {
183
+ id: '1',
184
+ todos: [{ id: '5', title: 'finish collections', userId: '1' }],
185
+ username: 'bob',
186
+ },
187
+ );
188
+ await flush();
189
+
190
+ expect(wrapper.text()).toBe('1');
191
+ });
192
+
193
+ it('works with unions collections (sanity)', async () => {
194
+ // Keep this light: verify we can call useQuery on a list schema and get an array
195
+ const list = useQuery(ArticleResource.getList.schema);
196
+ const Comp = defineComponent({
197
+ setup: () => () => h('div', (list.value || []).length),
198
+ });
199
+ const wrapper = mount(ProvideWrapper, {
200
+ slots: { default: () => h(Comp) },
201
+ });
202
+ const { controller }: any = wrapper.vm as any;
203
+ controller.setResponse(ArticleResource.getList, {}, []);
204
+ await flush();
205
+ expect(wrapper.text()).toBe('0');
206
+ });
207
+ });
@@ -0,0 +1,151 @@
1
+ import { mount } from '@vue/test-utils';
2
+ import nock from 'nock';
3
+ import { defineComponent, h, nextTick, Suspense } from 'vue';
4
+
5
+ // Endpoints/entities from React subscriptions test
6
+ import {
7
+ PollingArticleResource,
8
+ ArticleResource,
9
+ } from '../../../../__tests__/new';
10
+ import useSubscription from '../consumers/useSubscription';
11
+ import useSuspense from '../consumers/useSuspense';
12
+ import { provideDataClient } from '../providers/provideDataClient';
13
+
14
+ describe('vue useSubscription()', () => {
15
+ const payload = {
16
+ id: 5,
17
+ title: 'hi ho',
18
+ content: 'whatever',
19
+ tags: ['a', 'best', 'react'],
20
+ };
21
+
22
+ // Mutable payload to simulate server-side updates with polling
23
+ let currentPollingPayload: typeof payload = { ...payload };
24
+
25
+ async function flushUntil(
26
+ wrapper: any,
27
+ predicate: () => boolean,
28
+ tries = 100,
29
+ ) {
30
+ for (let i = 0; i < tries; i++) {
31
+ if (predicate()) return;
32
+ await Promise.resolve();
33
+ await nextTick();
34
+ await new Promise(resolve => setTimeout(resolve, 0));
35
+ }
36
+ }
37
+
38
+ beforeAll(() => {
39
+ // Global network stubs reused by tests
40
+ nock(/.*/)
41
+ .persist()
42
+ .defaultReplyHeaders({
43
+ 'Access-Control-Allow-Origin': '*',
44
+ 'Access-Control-Allow-Headers': 'Access-Token',
45
+ 'Content-Type': 'application/json',
46
+ })
47
+ .options(/.*/)
48
+ .reply(200)
49
+ // ArticleResource and PollingArticleResource both hit /article/:id
50
+ .get(`/article/${payload.id}`)
51
+ .reply(200, () => currentPollingPayload)
52
+ .put(`/article/${payload.id}`)
53
+ .reply(200, (uri, requestBody: any) => ({
54
+ ...currentPollingPayload,
55
+ ...requestBody,
56
+ }));
57
+ });
58
+
59
+ afterAll(() => {
60
+ nock.cleanAll();
61
+ });
62
+
63
+ const ProvideWrapper = defineComponent({
64
+ name: 'ProvideWrapper',
65
+ setup(_props, { slots, expose }) {
66
+ const { controller } = provideDataClient();
67
+ expose({ controller });
68
+ return () =>
69
+ h(
70
+ Suspense,
71
+ {},
72
+ {
73
+ default: () => (slots.default ? slots.default() : null),
74
+ fallback: () => h('div', { class: 'fallback' }, 'Loading'),
75
+ },
76
+ );
77
+ },
78
+ });
79
+
80
+ const ArticleComp = defineComponent({
81
+ name: 'ArticleComp',
82
+ props: { active: { type: Boolean, default: true } },
83
+ async setup(props) {
84
+ // Subscribe BEFORE any await to preserve current instance for inject()
85
+ useSubscription(
86
+ PollingArticleResource.get,
87
+ props.active ? { id: payload.id } : (null as any),
88
+ );
89
+ const article = await useSuspense(PollingArticleResource.get, {
90
+ id: payload.id,
91
+ });
92
+ return () =>
93
+ h('div', [
94
+ h('h3', (article as any).value.title),
95
+ h('p', (article as any).value.content),
96
+ ]);
97
+ },
98
+ });
99
+
100
+ it('subscribes and re-renders on updates (simulated poll)', async () => {
101
+ currentPollingPayload = { ...payload };
102
+
103
+ const wrapper = mount(ProvideWrapper, {
104
+ slots: { default: () => h(ArticleComp, { active: true }) },
105
+ });
106
+
107
+ // Initially should render fallback while Suspense is pending
108
+ expect(wrapper.find('.fallback').exists()).toBe(true);
109
+
110
+ // Flush initial fetch
111
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
112
+
113
+ // Verify initial values
114
+ expect(wrapper.find('h3').text()).toBe(payload.title);
115
+ expect(wrapper.find('p').text()).toBe(payload.content);
116
+
117
+ // Simulate a polling update by changing server payload and manually fetching
118
+ const updatedTitle = payload.title + ' fiver';
119
+ currentPollingPayload = { ...payload, title: updatedTitle } as any;
120
+ const exposed: any = wrapper.vm as any;
121
+ await exposed.controller.fetch(PollingArticleResource.get, {
122
+ id: payload.id,
123
+ });
124
+
125
+ await flushUntil(wrapper, () => wrapper.find('h3').text() === updatedTitle);
126
+ expect(wrapper.find('h3').text()).toBe(updatedTitle);
127
+ });
128
+
129
+ it('can subscribe to endpoint without pollFrequency (no-op) and render', async () => {
130
+ // Minimal component that subscribes to non-polling endpoint
131
+ const NoFreqComp = defineComponent({
132
+ name: 'NoFreqComp',
133
+ async setup() {
134
+ // Subscribe first (no poller attached)
135
+ useSubscription(ArticleResource.get, { id: payload.id } as any);
136
+ // Then resolve suspense for stable render
137
+ const article = await useSuspense(ArticleResource.get, {
138
+ id: payload.id,
139
+ });
140
+ return () => h('div', (article as any).value.title);
141
+ },
142
+ });
143
+
144
+ const wrapper = mount(ProvideWrapper, {
145
+ slots: { default: () => h(NoFreqComp) },
146
+ });
147
+
148
+ await flushUntil(wrapper, () => wrapper.text() !== '');
149
+ expect(wrapper.text()).not.toEqual('');
150
+ });
151
+ });
@@ -0,0 +1,159 @@
1
+ import { mount } from '@vue/test-utils';
2
+ import nock from 'nock';
3
+ import { defineComponent, h, nextTick, Suspense } from 'vue';
4
+
5
+ // Reuse the same endpoints/fixtures used by the React tests
6
+ import { CoolerArticleResource } from '../../../../__tests__/new';
7
+ // Minimal shared fixture (copied from React test fixtures)
8
+ const payload = {
9
+ id: 5,
10
+ title: 'hi ho',
11
+ content: 'whatever',
12
+ tags: ['a', 'best', 'react'],
13
+ };
14
+ import useSuspense from '../consumers/useSuspense';
15
+ import { provideDataClient } from '../providers/provideDataClient';
16
+
17
+ describe('vue useSuspense()', () => {
18
+ async function flushUntil(
19
+ wrapper: any,
20
+ predicate: () => boolean,
21
+ tries = 100,
22
+ ) {
23
+ for (let i = 0; i < tries; i++) {
24
+ if (predicate()) return;
25
+ await Promise.resolve();
26
+ await nextTick();
27
+ await new Promise(resolve => setTimeout(resolve, 0));
28
+ }
29
+ }
30
+
31
+ beforeAll(() => {
32
+ nock(/.*/)
33
+ .persist()
34
+ .defaultReplyHeaders({
35
+ 'Access-Control-Allow-Origin': '*',
36
+ 'Access-Control-Allow-Headers': 'Access-Token',
37
+ 'Content-Type': 'application/json',
38
+ })
39
+ .options(/.*/)
40
+ .reply(200)
41
+ .get(`/article-cooler/${payload.id}`)
42
+ .reply(200, payload)
43
+ .put(`/article-cooler/${payload.id}`)
44
+ .reply(200, (uri, requestBody: any) => ({
45
+ ...payload,
46
+ ...requestBody,
47
+ }));
48
+ });
49
+
50
+ afterAll(() => {
51
+ nock.cleanAll();
52
+ });
53
+
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
+ });
84
+
85
+ it('suspends on empty store, then renders after fetch resolves', async () => {
86
+ const wrapper = mount(ProvideWrapper, {
87
+ slots: { default: () => h(ArticleComp) },
88
+ });
89
+
90
+ // Initially should render fallback while Suspense is pending
91
+ expect(wrapper.find('.fallback').exists()).toBe(true);
92
+
93
+ // Flush pending promises/ticks until content renders
94
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
95
+
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);
102
+ });
103
+
104
+ it('re-renders when controller.setResponse() updates data', async () => {
105
+ const wrapper = mount(ProvideWrapper, {
106
+ slots: { default: () => h(ArticleComp) },
107
+ });
108
+ // Wait for initial render
109
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
110
+
111
+ // Verify initial values
112
+ expect(wrapper.find('h3').text()).toBe(payload.title);
113
+ expect(wrapper.find('p').text()).toBe(payload.content);
114
+
115
+ // Update the store using controller.setResponse
116
+ const exposed: any = wrapper.vm as any;
117
+ const newTitle = payload.title + ' updated';
118
+ const newContent = (payload as any).content + ' v2';
119
+ exposed.controller.setResponse(
120
+ CoolerArticleResource.get,
121
+ { id: payload.id },
122
+ { ...payload, title: newTitle, content: newContent },
123
+ );
124
+
125
+ await flushUntil(wrapper, () => wrapper.find('h3').text() === newTitle);
126
+
127
+ expect(wrapper.find('h3').text()).toBe(newTitle);
128
+ expect(wrapper.find('p').text()).toBe(newContent);
129
+ });
130
+
131
+ it('re-renders when controller.fetch() mutates data', async () => {
132
+ const wrapper = mount(ProvideWrapper, {
133
+ slots: { default: () => h(ArticleComp) },
134
+ });
135
+ // Wait for initial render
136
+ await flushUntil(wrapper, () => wrapper.find('h3').exists());
137
+
138
+ // Verify initial values
139
+ expect(wrapper.find('h3').text()).toBe(payload.title);
140
+ expect(wrapper.find('p').text()).toBe(payload.content);
141
+
142
+ // Mutate the data using controller.fetch with update endpoint
143
+ const exposed: any = wrapper.vm as any;
144
+ const updatedTitle = payload.title + ' mutated';
145
+ const updatedContent = payload.content + ' mutated';
146
+
147
+ await exposed.controller.fetch(
148
+ CoolerArticleResource.update,
149
+ { id: payload.id },
150
+ { title: updatedTitle, content: updatedContent },
151
+ );
152
+
153
+ // Wait for re-render with new data
154
+ await flushUntil(wrapper, () => wrapper.find('h3').text() === updatedTitle);
155
+
156
+ expect(wrapper.find('h3').text()).toBe(updatedTitle);
157
+ expect(wrapper.find('p').text()).toBe(updatedContent);
158
+ });
159
+ });
@@ -0,0 +1,26 @@
1
+ import { Controller as DataController } from '@data-client/core';
2
+ import type { State, Manager, GCInterface } from '@data-client/core';
3
+ import { defineComponent } from 'vue';
4
+
5
+ import { provideDataClient } from '../providers/provideDataClient.js';
6
+
7
+ export interface ProviderProps {
8
+ managers?: Manager[];
9
+ initialState?: State<unknown>;
10
+ Controller?: typeof DataController;
11
+ gcPolicy?: GCInterface;
12
+ }
13
+
14
+ export default defineComponent<ProviderProps>({
15
+ name: 'DataProvider',
16
+ props: ['managers', 'initialState', 'Controller', 'gcPolicy'] as any,
17
+ setup(props, { slots }) {
18
+ provideDataClient({
19
+ Controller: props.Controller,
20
+ gcPolicy: props.gcPolicy,
21
+ initialState: props.initialState,
22
+ managers: props.managers,
23
+ });
24
+ return () => (slots.default ? slots.default() : null);
25
+ },
26
+ });
@@ -0,0 +1,7 @@
1
+ export { default as useSuspense } from './useSuspense.js';
2
+ export { default as useSubscription } from './useSubscription.js';
3
+ export { default as useQuery } from './useQuery.js';
4
+ export {
5
+ injectController as useController,
6
+ injectState as useStateRef,
7
+ } from '../context.js';
@@ -0,0 +1,12 @@
1
+ import type { State } from '@data-client/core';
2
+ import type { ShallowRef } from 'vue';
3
+
4
+ import { injectController, injectState } from '../context.js';
5
+
6
+ export function useController() {
7
+ return injectController();
8
+ }
9
+
10
+ export function useStateRef(): ShallowRef<State<unknown>> {
11
+ return injectState();
12
+ }
@@ -0,0 +1,43 @@
1
+ import type {
2
+ DenormalizeNullable,
3
+ NI,
4
+ Queryable,
5
+ SchemaArgs,
6
+ } from '@data-client/core';
7
+ import { computed, watch, type ComputedRef } from 'vue';
8
+
9
+ import { injectController, injectState } from '../context.js';
10
+
11
+ /**
12
+ * Query the store (non-suspense).
13
+ *
14
+ * Returns a readonly computed ref of the query result. The value is undefined when
15
+ * the result is not found or invalid.
16
+ * Mirrors React's useQuery semantics using Vue reactivity.
17
+ * @see https://dataclient.io/docs/api/useQuery
18
+ */
19
+ export default function useQuery<S extends Queryable>(
20
+ schema: S,
21
+ ...args: NI<SchemaArgs<S>>
22
+ ): ComputedRef<DenormalizeNullable<S> | undefined> {
23
+ const stateRef = injectState();
24
+ const controller = injectController();
25
+
26
+ // Compute query meta based on state and args. This mirrors React's memoization
27
+ // that keys off state.entities/indexes and args.
28
+ const queryMeta = computed(() =>
29
+ controller.getQueryMeta(schema, ...args, stateRef.value as any),
30
+ );
31
+
32
+ // Maintain GC refcounts on data mount/changes
33
+ watch(
34
+ () => queryMeta.value.data,
35
+ (_newVal, _oldVal, onCleanup) => {
36
+ const decrement = queryMeta.value.countRef();
37
+ onCleanup(() => decrement());
38
+ },
39
+ { immediate: true },
40
+ );
41
+
42
+ return computed(() => queryMeta.value.data);
43
+ }
@@ -0,0 +1,44 @@
1
+ import type {
2
+ EndpointInterface,
3
+ Schema,
4
+ FetchFunction,
5
+ } from '@data-client/core';
6
+ import { computed, unref, watch } from 'vue';
7
+
8
+ import { injectController } from '../context.js';
9
+
10
+ /**
11
+ * Keeps a resource fresh by subscribing to updates.
12
+ * Mirrors React hook API. Pass `null` as first arg to unsubscribe.
13
+ * @see https://dataclient.io/docs/api/useSubscription
14
+ */
15
+ export default function useSubscription<
16
+ E extends EndpointInterface<
17
+ FetchFunction,
18
+ Schema | undefined,
19
+ undefined | false
20
+ >,
21
+ >(endpoint: E, ...args: readonly [...Parameters<E>] | readonly [null]) {
22
+ const controller = injectController();
23
+
24
+ // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger resubscribe.
25
+ const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
26
+ const key = computed(() => {
27
+ if (resolvedArgs.value[0] === null) return '';
28
+ return endpoint.key(...(resolvedArgs.value as readonly [...Parameters<E>]));
29
+ });
30
+
31
+ // Subscribe when key exists; unsubscribe on change or unmount
32
+ watch(
33
+ key,
34
+ (_newKey, _oldKey, onCleanup) => {
35
+ if (!key.value) return;
36
+ const cleanedArgs = resolvedArgs.value as readonly [...Parameters<E>];
37
+ controller.subscribe(endpoint, ...cleanedArgs);
38
+ onCleanup(() => {
39
+ controller.unsubscribe(endpoint, ...cleanedArgs);
40
+ });
41
+ },
42
+ { immediate: true },
43
+ );
44
+ }