@data-client/vue 0.0.4 → 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 (75) 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/index.d.ts.map +1 -1
  9. package/lib/providers/DataClientPlugin.d.ts +22 -0
  10. package/lib/providers/DataClientPlugin.d.ts.map +1 -0
  11. package/lib/providers/DataClientPlugin.js +40 -0
  12. package/lib/providers/{provideDataClient.d.ts → createDataClient.d.ts} +10 -6
  13. package/lib/providers/createDataClient.d.ts.map +1 -0
  14. package/lib/providers/createDataClient.js +103 -0
  15. package/lib/providers/index.d.ts +2 -1
  16. package/lib/providers/index.d.ts.map +1 -1
  17. package/lib/providers/index.js +3 -2
  18. package/lib/test/MockController.d.ts +8 -0
  19. package/lib/test/MockController.d.ts.map +1 -0
  20. package/lib/test/MockController.js +125 -0
  21. package/lib/test/collapseFixture.d.ts +6 -0
  22. package/lib/test/collapseFixture.d.ts.map +1 -0
  23. package/lib/test/collapseFixture.js +19 -0
  24. package/lib/test/createFixtureMap.d.ts +3 -0
  25. package/lib/test/createFixtureMap.d.ts.map +1 -0
  26. package/lib/test/createFixtureMap.js +23 -0
  27. package/lib/test/fixtureTypes.d.ts +99 -0
  28. package/lib/test/fixtureTypes.d.ts.map +1 -0
  29. package/lib/test/fixtureTypes.js +2 -0
  30. package/lib/test/index.d.ts +8 -0
  31. package/lib/test/index.d.ts.map +1 -0
  32. package/lib/test/index.js +7 -0
  33. package/lib/test/mockState.d.ts +4 -0
  34. package/lib/test/mockState.d.ts.map +1 -0
  35. package/lib/test/mockState.js +44 -0
  36. package/lib/test/renderDataClient.d.ts +40 -0
  37. package/lib/test/renderDataClient.d.ts.map +1 -0
  38. package/lib/test/renderDataClient.js +264 -0
  39. package/package.json +13 -6
  40. package/src/__tests__/__snapshots__/useQuery.web.ts.snap +126 -0
  41. package/src/__tests__/__snapshots__/useSubscription.web.ts.snap +7 -0
  42. package/src/__tests__/integration-garbage-collection.web.ts +155 -0
  43. package/src/__tests__/useFetch.web.ts +192 -51
  44. package/src/__tests__/useLive.web.ts +66 -34
  45. package/src/__tests__/useQuery.web.ts +263 -109
  46. package/src/__tests__/useSubscription.web.ts +16 -3
  47. package/src/__tests__/useSuspense.web.ts +141 -70
  48. package/src/consumers/useFetch.ts +16 -9
  49. package/src/consumers/useSuspense.ts +37 -15
  50. package/src/context.ts +2 -0
  51. package/src/providers/DataClientPlugin.ts +39 -0
  52. package/src/providers/__tests__/DataClientPlugin.test.ts +387 -0
  53. package/src/providers/{provideDataClient.ts → createDataClient.ts} +33 -24
  54. package/src/providers/index.ts +2 -1
  55. package/src/test/MockController.ts +151 -0
  56. package/src/test/README.md +245 -0
  57. package/src/test/collapseFixture.ts +21 -0
  58. package/src/test/createFixtureMap.ts +26 -0
  59. package/src/test/fixtureTypes.ts +121 -0
  60. package/src/test/index.ts +23 -0
  61. package/src/test/mockState.ts +57 -0
  62. package/src/test/renderDataClient.ts +316 -0
  63. package/ts3.4/providers/DataClientPlugin.d.ts +22 -0
  64. package/ts3.4/providers/createDataClient.d.ts +25 -0
  65. package/ts3.4/providers/index.d.ts +2 -1
  66. package/ts3.4/test/MockController.d.ts +8 -0
  67. package/ts3.4/test/collapseFixture.d.ts +6 -0
  68. package/ts3.4/test/createFixtureMap.d.ts +6 -0
  69. package/ts3.4/test/fixtureTypes.d.ts +99 -0
  70. package/ts3.4/test/index.d.ts +8 -0
  71. package/ts3.4/test/mockState.d.ts +4 -0
  72. package/ts3.4/test/renderDataClient.d.ts +40 -0
  73. package/lib/providers/provideDataClient.d.ts.map +0 -1
  74. package/lib/providers/provideDataClient.js +0 -94
  75. package/ts3.4/providers/provideDataClient.d.ts +0 -21
@@ -1,16 +1,18 @@
1
1
  import { schema } from '@data-client/endpoint';
2
2
  import { resource } from '@data-client/rest';
3
- import { mount } from '@vue/test-utils';
4
- import { defineComponent, h, nextTick } from 'vue';
5
3
 
6
4
  import {
7
5
  ArticleWithSlug,
8
6
  ArticleSlugResource,
9
7
  ArticleResource,
8
+ Article,
10
9
  IDEntity,
10
+ UnionSchema,
11
+ FirstUnion,
12
+ SecondUnion,
11
13
  } from '../../../../__tests__/new';
12
14
  import useQuery from '../consumers/useQuery';
13
- import { provideDataClient } from '../providers/provideDataClient';
15
+ import { renderDataComposable } from '../test/renderDataClient';
14
16
 
15
17
  // Inline fixtures (duplicated from React tests to avoid cross-project imports)
16
18
  const payloadSlug = {
@@ -20,6 +22,7 @@ const payloadSlug = {
20
22
  content: 'whatever',
21
23
  tags: ['a', 'best', 'react'],
22
24
  };
25
+
23
26
  const nested = [
24
27
  {
25
28
  id: 5,
@@ -44,104 +47,142 @@ const nested = [
44
47
  ];
45
48
 
46
49
  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
- },
50
+ it('should be undefined with empty state', () => {
51
+ const { result } = renderDataComposable(() => {
52
+ return useQuery(ArticleWithSlug, { id: payloadSlug.id });
53
+ }, {});
54
+ // @ts-expect-error
55
+ result.current?.value?.doesnotexist;
56
+ expect(result.current?.value).toBe(undefined);
59
57
  });
60
58
 
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
- });
59
+ it('All should be undefined with empty state', () => {
60
+ const { result } = renderDataComposable(() => {
61
+ return useQuery(new schema.All(ArticleWithSlug));
62
+ }, {});
63
+ // @ts-expect-error
64
+ result.current?.value?.doesnotexist;
65
+ expect(result.current?.value).toBe(undefined);
66
+ });
68
67
 
69
- const wrapper = mount(ProvideWrapper, {
70
- slots: { default: () => h(Inner) },
71
- });
72
- await flush();
73
- expect(wrapper.text()).toBe('');
68
+ it('should fail on schema.Array', () => {
69
+ const { result } = renderDataComposable(() => {
70
+ // @ts-expect-error
71
+ return useQuery(new schema.Array(ArticleWithSlug));
72
+ }, {});
73
+ // @ts-expect-error
74
+ result.current?.value?.doesnotexist;
75
+ expect(result.current?.value).toBe(undefined);
74
76
  });
75
77
 
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
- );
78
+ it('should find Entity by pk', async () => {
79
+ const { result } = renderDataComposable(
80
+ () => {
81
+ return useQuery(ArticleWithSlug, { id: payloadSlug.id });
82
+ },
83
+ {
84
+ initialFixtures: [
85
+ {
86
+ endpoint: ArticleSlugResource.get,
87
+ args: [{ id: 5 }],
88
+ response: payloadSlug,
89
+ },
90
+ ],
88
91
  },
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
92
  );
102
- await flush();
93
+ expect(result.current?.value).toEqual(ArticleWithSlug.fromJS(payloadSlug));
103
94
 
104
- expect(wrapper.text()).toContain(payloadSlug.title);
95
+ // @ts-expect-error
96
+ () => useQuery(ArticleWithSlug);
97
+ // @ts-expect-error
98
+ () => useQuery(ArticleWithSlug, 5, 10);
99
+ // @ts-expect-error
100
+ () => useQuery(ArticleWithSlug, 5);
101
+ // @ts-expect-error
102
+ () => useQuery(ArticleWithSlug, { id5: 5 });
103
+ // @ts-expect-error
104
+ () => useQuery(ArticleWithSlug, '5');
105
105
  });
106
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(','));
107
+ it('should find Entity by slug', async () => {
108
+ const { result } = renderDataComposable(
109
+ () => {
110
+ return useQuery(ArticleWithSlug, { slug: payloadSlug.slug });
113
111
  },
114
- });
115
-
116
- const wrapper = mount(ProvideWrapper, {
117
- slots: { default: () => h(ListComp) },
118
- });
119
- const { controller }: any = wrapper.vm as any;
112
+ {
113
+ initialFixtures: [
114
+ {
115
+ endpoint: ArticleSlugResource.get,
116
+ args: [{ id: 5 }],
117
+ response: payloadSlug,
118
+ },
119
+ ],
120
+ },
121
+ );
122
+ expect(result.current?.value).toEqual(ArticleWithSlug.fromJS(payloadSlug));
123
+ });
120
124
 
121
- controller.setResponse(ArticleResource.getList, {}, nested);
122
- await flush();
123
- expect(wrapper.text().split(',').filter(Boolean).length).toBe(
124
- nested.length,
125
+ it('should select Collections', () => {
126
+ const initialFixtures = [
127
+ {
128
+ endpoint: ArticleResource.getList,
129
+ args: [],
130
+ response: nested,
131
+ },
132
+ ];
133
+ const { result } = renderDataComposable(
134
+ () => {
135
+ return useQuery(ArticleResource.getList.schema);
136
+ },
137
+ { initialFixtures },
125
138
  );
139
+ expect(result.current?.value).toBeDefined();
140
+ if (!result.current?.value) return;
141
+ expect(result.current.value.length).toBe(nested.length);
142
+ expect(result.current.value[0]).toBeInstanceOf(Article);
143
+ expect(result.current.value).toMatchSnapshot();
144
+ });
126
145
 
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,
146
+ it('should update Collections when pushed', async () => {
147
+ const initialFixtures = [
148
+ {
149
+ endpoint: ArticleResource.getList,
150
+ args: [],
151
+ response: nested,
152
+ },
153
+ ];
154
+ const resolverFixtures = [
155
+ {
156
+ endpoint: ArticleResource.getList.push,
157
+ response(body: any) {
158
+ return body;
159
+ },
160
+ },
161
+ ];
162
+ const { result, controller, waitForNextUpdate } = renderDataComposable(
163
+ () => {
164
+ return useQuery(ArticleResource.getList.schema, {});
165
+ },
166
+ { initialFixtures, resolverFixtures },
137
167
  );
168
+ expect(result.current?.value).toBeDefined();
169
+ if (!result.current?.value) return;
170
+ expect(result.current.value.length).toBe(nested.length);
171
+ await controller.fetch(ArticleResource.getList.push, {
172
+ id: 50,
173
+ title: 'newly added',
174
+ content: 'this one is pushed',
175
+ });
176
+ await waitForNextUpdate();
177
+ expect(result.current.value.length).toBe(nested.length + 1);
138
178
  });
139
179
 
140
- it('retrieves a nested collection (Collection of Array)', async () => {
180
+ it('should retrieve a nested collection', () => {
141
181
  class Todo extends IDEntity {
142
182
  userId = 0;
143
183
  title = '';
144
184
  completed = false;
185
+
145
186
  static key = 'Todo';
146
187
  }
147
188
 
@@ -150,58 +191,171 @@ describe('vue useQuery()', () => {
150
191
  username = '';
151
192
  email = '';
152
193
  todos: Todo[] = [];
194
+
153
195
  static key = 'User';
154
196
  static schema = {
155
197
  todos: new schema.Collection(new schema.Array(Todo), {
156
- nestKey: (parent: any) => ({ userId: parent.id }),
198
+ nestKey: parent => ({
199
+ userId: parent.id,
200
+ }),
157
201
  }),
158
202
  };
159
203
  }
160
204
 
161
205
  const userTodos = new schema.Collection(new schema.Array(Todo), {
162
- argsKey: ({ userId }: { userId: string }) => ({ userId }),
206
+ argsKey: ({ userId }: { userId: string }) => ({
207
+ userId,
208
+ }),
163
209
  });
164
210
 
165
211
  const UserResource = resource({ schema: User, path: '/users/:id' });
166
212
 
167
- const Inner = defineComponent({
168
- setup() {
169
- const todos = useQuery(userTodos, { userId: '1' });
170
- return () => h('div', (todos.value || []).length.toString());
213
+ const initialFixtures = [
214
+ {
215
+ endpoint: UserResource.get,
216
+ args: [{ id: '1' }],
217
+ response: {
218
+ id: '1',
219
+ todos: [
220
+ {
221
+ id: '5',
222
+ title: 'finish collections',
223
+ userId: '1',
224
+ },
225
+ ],
226
+ username: 'bob',
227
+ },
171
228
  },
172
- });
229
+ ];
230
+ const { result } = renderDataComposable(
231
+ () => {
232
+ return useQuery(userTodos, { userId: '1' });
233
+ },
234
+ { initialFixtures },
235
+ );
236
+ expect(result.current?.value).toBeDefined();
237
+ if (!result.current?.value) return;
238
+ expect(result.current.value.length).toBe(1);
239
+ expect(result.current.value[0]).toBeInstanceOf(Todo);
240
+ expect(result.current.value).toMatchSnapshot();
173
241
 
174
- const wrapper = mount(ProvideWrapper, {
175
- slots: { default: () => h(Inner) },
242
+ // @ts-expect-error
243
+ () => useQuery(userTodos, { userId: { hi: '5' } });
244
+ // @ts-expect-error
245
+ () => useQuery(userTodos, { userIdd: '1' });
246
+ // @ts-expect-error
247
+ () => useQuery(userTodos, { bob: '1' });
248
+ // @ts-expect-error
249
+ () => useQuery(userTodos);
250
+ });
251
+
252
+ it('should work with unions', async () => {
253
+ const warnSpy = jest
254
+ .spyOn(global.console, 'warn')
255
+ .mockImplementation(() => {
256
+ // noop
257
+ });
258
+ const UnionResource = resource({
259
+ path: '/union/:id',
260
+ schema: UnionSchema,
176
261
  });
177
- const { controller }: any = wrapper.vm as any;
178
262
 
179
- controller.setResponse(
180
- UserResource.get,
181
- { id: '1' },
263
+ const { result } = renderDataComposable(
264
+ () => {
265
+ return useQuery(UnionResource.get.schema, { id: '5', type: 'first' });
266
+ },
182
267
  {
183
- id: '1',
184
- todos: [{ id: '5', title: 'finish collections', userId: '1' }],
185
- username: 'bob',
268
+ initialFixtures: [
269
+ {
270
+ endpoint: UnionResource.getList,
271
+ args: [],
272
+ response: [
273
+ { id: '5', body: 'hi', type: 'first' },
274
+ { id: '6', body: 'hi', type: 'another' },
275
+ ],
276
+ },
277
+ ],
186
278
  },
187
279
  );
188
- await flush();
280
+ expect(result.current?.value).toBeDefined();
281
+ if (!result.current?.value) {
282
+ warnSpy.mockRestore();
283
+ return;
284
+ }
285
+ expect(result.current.value.type).toBe('first');
286
+ expect(result.current.value).toBeInstanceOf(FirstUnion);
189
287
 
190
- expect(wrapper.text()).toBe('1');
288
+ // these are the 'fallback case' where it cannot determine type discriminator, so just enumerates
289
+ () => useQuery(UnionResource.get.schema, { id: '5' });
290
+ () => useQuery(UnionResource.get.schema, { body: '5' });
291
+
292
+ // @ts-expect-error
293
+ () => useQuery(UnionResource.get.schema, { id: '5', type: 'notvalid' });
294
+ // @ts-expect-error
295
+ () => useQuery(UnionResource.get.schema, { doesnotexist: '5' });
296
+ // @ts-expect-error
297
+ () => useQuery(UnionResource.get.schema);
298
+
299
+ expect(warnSpy.mock.calls).toMatchSnapshot();
300
+ warnSpy.mockRestore();
191
301
  });
192
302
 
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),
303
+ it('should work with unions collections', async () => {
304
+ const warnSpy = jest
305
+ .spyOn(global.console, 'warn')
306
+ .mockImplementation(() => {
307
+ // noop
308
+ });
309
+
310
+ const UnionResource = resource({
311
+ path: '/union/:id',
312
+ schema: UnionSchema,
198
313
  });
199
- const wrapper = mount(ProvideWrapper, {
200
- slots: { default: () => h(Comp) },
314
+
315
+ const { result, controller, waitForNextUpdate } = renderDataComposable(
316
+ () => {
317
+ return useQuery(UnionResource.getList.schema);
318
+ },
319
+ {
320
+ initialFixtures: [
321
+ {
322
+ endpoint: UnionResource.getList,
323
+ args: [],
324
+ response: [
325
+ undefined,
326
+ null,
327
+ { id: '5', body: 'hi', type: 'first' },
328
+ { id: '6', body: 'hi', type: 'another' },
329
+ { id: '7', body: 'hi' },
330
+ ],
331
+ },
332
+ ],
333
+ resolverFixtures: [
334
+ {
335
+ endpoint: UnionResource.getList.push,
336
+ response(body) {
337
+ return body;
338
+ },
339
+ },
340
+ ],
341
+ },
342
+ );
343
+ expect(result.current?.value).toBeDefined();
344
+ if (!result.current?.value) return;
345
+ expect(result.current.value[0]).toBeNull();
346
+ expect(result.current.value[1]).toBeInstanceOf(FirstUnion);
347
+ expect(result.current.value[2]).not.toBeInstanceOf(FirstUnion);
348
+ expect(result.current.value[3]).not.toBeInstanceOf(FirstUnion);
349
+ expect(warnSpy.mock.calls).toMatchSnapshot();
350
+
351
+ await controller.fetch(UnionResource.getList.push, {
352
+ body: 'hi',
353
+ type: 'second',
354
+ id: '100',
201
355
  });
202
- const { controller }: any = wrapper.vm as any;
203
- controller.setResponse(ArticleResource.getList, {}, []);
204
- await flush();
205
- expect(wrapper.text()).toBe('0');
356
+ await waitForNextUpdate();
357
+ expect(result.current.value[4]).toBeInstanceOf(SecondUnion);
358
+ expect(result.current.value).toMatchSnapshot();
359
+ warnSpy.mockRestore();
206
360
  });
207
361
  });
@@ -1,6 +1,6 @@
1
1
  import { mount } from '@vue/test-utils';
2
2
  import nock from 'nock';
3
- import { defineComponent, h, nextTick, Suspense } from 'vue';
3
+ import { defineComponent, h, nextTick, Suspense, inject } from 'vue';
4
4
 
5
5
  // Endpoints/entities from React subscriptions test
6
6
  import {
@@ -9,7 +9,8 @@ import {
9
9
  } from '../../../../__tests__/new';
10
10
  import useSubscription from '../consumers/useSubscription';
11
11
  import useSuspense from '../consumers/useSuspense';
12
- import { provideDataClient } from '../providers/provideDataClient';
12
+ import { ControllerKey } from '../context';
13
+ import { DataClientPlugin } from '../providers/DataClientPlugin';
13
14
 
14
15
  describe('vue useSubscription()', () => {
15
16
  const payload = {
@@ -63,7 +64,7 @@ describe('vue useSubscription()', () => {
63
64
  const ProvideWrapper = defineComponent({
64
65
  name: 'ProvideWrapper',
65
66
  setup(_props, { slots, expose }) {
66
- const { controller } = provideDataClient();
67
+ const controller = inject(ControllerKey);
67
68
  expose({ controller });
68
69
  return () =>
69
70
  h(
@@ -102,6 +103,9 @@ describe('vue useSubscription()', () => {
102
103
 
103
104
  const wrapper = mount(ProvideWrapper, {
104
105
  slots: { default: () => h(ArticleComp, { active: true }) },
106
+ global: {
107
+ plugins: [[DataClientPlugin]],
108
+ },
105
109
  });
106
110
 
107
111
  // Initially should render fallback while Suspense is pending
@@ -127,6 +131,9 @@ describe('vue useSubscription()', () => {
127
131
  });
128
132
 
129
133
  it('can subscribe to endpoint without pollFrequency (no-op) and render', async () => {
134
+ const oldError = console.error;
135
+ const spy = (console.error = jest.fn());
136
+
130
137
  // Minimal component that subscribes to non-polling endpoint
131
138
  const NoFreqComp = defineComponent({
132
139
  name: 'NoFreqComp',
@@ -143,9 +150,15 @@ describe('vue useSubscription()', () => {
143
150
 
144
151
  const wrapper = mount(ProvideWrapper, {
145
152
  slots: { default: () => h(NoFreqComp) },
153
+ global: {
154
+ plugins: [[DataClientPlugin]],
155
+ },
146
156
  });
147
157
 
148
158
  await flushUntil(wrapper, () => wrapper.text() !== '');
149
159
  expect(wrapper.text()).not.toEqual('');
160
+ expect(spy.mock.calls[0]).toMatchSnapshot();
161
+
162
+ console.error = oldError;
150
163
  });
151
164
  });