-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathgeneral.ts
More file actions
1665 lines (1462 loc) · 39.6 KB
/
Copy pathgeneral.ts
File metadata and controls
1665 lines (1462 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { DocumentNode, GraphQLFormattedError } from "graphql";
import {
getIntrospectionQuery,
graphql,
GraphQLError,
GraphQLID,
GraphQLInt,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
print,
} from "graphql";
import { gql } from "graphql-tag";
import type { Observable } from "rxjs";
import { defer, delay, of } from "rxjs";
import { ApolloClient, NetworkStatus } from "@apollo/client";
import { InMemoryCache } from "@apollo/client/cache";
import { CombinedGraphQLErrors } from "@apollo/client/errors";
import { ApolloLink } from "@apollo/client/link";
import { LocalState } from "@apollo/client/local-state";
import { MockSubscriptionLink } from "@apollo/client/testing";
import {
ObservableStream,
spyOnConsole,
} from "@apollo/client/testing/internal";
import { InvariantError } from "@apollo/client/utilities/invariant";
const WARNINGS = {
MISSING_RESOLVER:
"Could not find a resolver for the '%s' field nor does the cache resolve the field. The field value has been set to `null`. Either define a resolver for the field or ensure the cache can resolve the value, for example, by adding a 'read' function to a field policy in 'InMemoryCache'.",
NO_CACHE:
"The '%s' field resolves the value from the cache, for example from a 'read' function, but a 'no-cache' fetch policy was used. The field value has been set to `null`. Either define a local resolver or use a fetch policy that uses the cache to ensure the field is resolved correctly.",
};
describe("General functionality", () => {
test("should not impact normal non-@client use", async () => {
const query = gql`
{
field
}
`;
const link = new ApolloLink(() => of({ data: { field: 1 } }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
localState: new LocalState({
resolvers: {
Query: {
count: () => 0,
},
},
}),
});
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: 1 },
});
});
test("should not interfere with server introspection queries", async () => {
const query = gql`
${getIntrospectionQuery()}
`;
const error = new GraphQLError("no introspection result found");
const link = new ApolloLink(() => of({ errors: [error] }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
localState: new LocalState({
resolvers: {
Query: {
count: () => 0,
},
},
}),
});
await expect(client.query({ query })).rejects.toThrow(/no introspection/);
});
test("should support returning default values from resolvers", async () => {
const query = gql`
{
field @client
}
`;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
localState: new LocalState({
resolvers: {
Query: {
field: () => 1,
},
},
}),
});
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: 1 },
});
});
test("should cache data for future lookups", async () => {
const query = gql`
{
field @client
}
`;
let count = 0;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
localState: new LocalState({
resolvers: {
Query: {
field: () => {
count += 1;
return 1;
},
},
},
}),
});
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: 1 },
});
expect(count).toBe(1);
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: 1 },
});
expect(count).toBe(1);
});
test("should honour `fetchPolicy` settings", async () => {
const query = gql`
{
field @client
}
`;
let count = 0;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
localState: new LocalState({
resolvers: {
Query: {
field: () => {
count += 1;
return 1;
},
},
},
}),
});
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: 1 },
});
expect(count).toBe(1);
await expect(
client.query({ query, fetchPolicy: "network-only" })
).resolves.toStrictEqualTyped({
data: { field: 1 },
});
expect(count).toBe(2);
});
test("can configure local state after client is initialized", async () => {
const query = gql`
query {
count @client
}
`;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
});
const localState = new LocalState({
resolvers: {
Query: {
count: () => 0,
},
},
});
client.localState = localState;
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { count: 0 },
});
});
});
describe("Cache manipulation", () => {
test("should be able to query @client fields and the cache without defining resolvers in local state", async () => {
const query = gql`
{
field @client
}
`;
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: ApolloLink.empty(),
localState: new LocalState(),
});
cache.writeQuery({ query, data: { field: "yo" } });
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: "yo" },
});
});
test("should be able to write to the cache using a local mutation", async () => {
const query = gql`
{
field @client
}
`;
const mutation = gql`
mutation start {
start @client
}
`;
const localState = new LocalState({
resolvers: {
Mutation: {
start: (_, __, { client }) => {
client.cache.writeQuery({ query, data: { field: 1 } });
return true;
},
},
},
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
localState,
});
await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({
data: { start: true },
});
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: 1 },
});
});
test("should be able to write to the cache with a local mutation and have things rerender automatically", async () => {
const query = gql`
{
field @client
}
`;
const mutation = gql`
mutation start {
start @client
}
`;
const localState = new LocalState({
resolvers: {
Query: {
field: () => 0,
},
Mutation: {
start: (_1: any, _2: any, { client }) => {
client.cache.writeQuery({ query, data: { field: 1 } });
return true;
},
},
},
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
localState,
});
const stream = new ObservableStream(client.watchQuery({ query }));
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
await expect(stream).toEmitTypedValue({
data: { field: 0 },
dataState: "complete",
loading: false,
networkStatus: NetworkStatus.ready,
partial: false,
});
await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({
data: { start: true },
});
await expect(stream).toEmitTypedValue({
data: { field: 1 },
dataState: "complete",
loading: false,
networkStatus: NetworkStatus.ready,
partial: false,
});
});
test("should support writing to the cache with a local mutation using variables", async () => {
const query = gql`
{
field @client
}
`;
const mutation = gql`
mutation start($id: ID!) {
start(field: $id) @client {
field
}
}
`;
const localState = new LocalState({
resolvers: {
Mutation: {
start: (_, variables: { field: string }, { client }) => {
client.cache.writeQuery({
query,
data: { field: variables.field },
});
return {
__typename: "Field",
field: variables.field,
};
},
},
},
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
localState,
});
await expect(
client.mutate({ mutation, variables: { id: "1234" } })
).resolves.toStrictEqualTyped({
data: { start: { field: "1234", __typename: "Field" } },
});
await expect(client.query({ query })).resolves.toStrictEqualTyped({
data: { field: "1234" },
});
});
test("should read @client fields from cache on refetch (#4741)", async () => {
const query = gql`
query FetchInitialData {
serverData {
id
title
}
selectedItemId @client
}
`;
const mutation = gql`
mutation Select {
select(itemId: $id) @client
}
`;
const serverData = {
__typename: "ServerData",
id: 123,
title: "Oyez and Onoz",
};
let selectedItemId = -1;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new ApolloLink(() => of({ data: { serverData } })),
localState: new LocalState({
resolvers: {
Query: {
selectedItemId() {
return selectedItemId;
},
},
Mutation: {
select(_, { itemId }) {
selectedItemId = itemId;
return itemId;
},
},
},
}),
});
const stream = new ObservableStream(client.watchQuery({ query }));
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
await expect(stream).toEmitTypedValue({
data: {
serverData,
selectedItemId: -1,
},
dataState: "complete",
loading: false,
networkStatus: 7,
partial: false,
});
await expect(
client.mutate({
mutation,
variables: { id: 123 },
refetchQueries: ["FetchInitialData"],
})
).resolves.toStrictEqualTyped({ data: { select: 123 } });
await expect(stream).toEmitTypedValue({
data: { serverData, selectedItemId: -1 },
dataState: "complete",
loading: true,
networkStatus: NetworkStatus.refetch,
partial: false,
});
await expect(stream).toEmitTypedValue({
data: {
serverData,
selectedItemId: 123,
},
dataState: "complete",
loading: false,
networkStatus: 7,
partial: false,
});
});
test("should rerun @client(always: true) fields on entity update", async () => {
const query = gql`
query GetClientData($id: ID) {
clientEntity(id: $id) @client(always: true) {
id
title
titleLength @client(always: true)
}
}
`;
const mutation = gql`
mutation AddOrUpdate {
addOrUpdate(id: $id, title: $title) @client
}
`;
const fragment = gql`
fragment ClientDataFragment on ClientData {
id
title
}
`;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new ApolloLink(() => of({ data: {} })),
localState: new LocalState({
resolvers: {
ClientData: {
titleLength(data) {
return data.title.length;
},
},
Query: {
clientEntity(_root, { id }, { client }) {
const { cache } = client;
return cache.readFragment({
id: cache.identify({ id, __typename: "ClientData" }),
fragment,
});
},
},
Mutation: {
addOrUpdate(_root, { id, title }, { client }) {
const { cache } = client;
return cache.writeFragment({
id: cache.identify({ id, __typename: "ClientData" }),
fragment,
data: { id, title, __typename: "ClientData" },
});
},
},
},
}),
});
const entityId = 1;
const shortTitle = "Short";
const longerTitle = "A little longer";
await client.mutate({
mutation,
variables: {
id: entityId,
title: shortTitle,
},
});
const stream = new ObservableStream(
client.watchQuery<any>({ query, variables: { id: entityId } })
);
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
{
const result = await stream.takeNext();
expect(result.data.clientEntity).toEqual({
id: entityId,
title: shortTitle,
titleLength: shortTitle.length,
__typename: "ClientData",
});
}
await client.mutate({
mutation,
variables: {
id: entityId,
title: longerTitle,
},
});
{
const result = await stream.takeNext();
expect(result.data.clientEntity).toEqual({
id: entityId,
title: longerTitle,
titleLength: longerTitle.length,
__typename: "ClientData",
});
}
await expect(stream).not.toEmitAnything();
});
test("runs read functions for nested @client fields without resolver warnings", async () => {
using _ = spyOnConsole("warn");
const query = gql`
query {
color {
hex
saved @client
}
}
`;
const link = new ApolloLink(() => {
return of({ data: { color: { __typename: "Color", hex: "#000" } } }).pipe(
delay(20)
);
});
const read = jest.fn(() => false);
const cache = new InMemoryCache({
typePolicies: {
Color: {
keyFields: ["hex"],
fields: {
saved: { read },
},
},
},
});
const client = new ApolloClient({
link,
cache,
localState: new LocalState(),
});
const stream = new ObservableStream(client.watchQuery({ query }));
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
await expect(stream).toEmitTypedValue({
data: { color: { __typename: "Color", hex: "#000", saved: false } },
dataState: "complete",
loading: false,
networkStatus: NetworkStatus.ready,
partial: false,
});
expect(read).toHaveBeenCalledTimes(1);
expect(read).toHaveBeenCalledWith(undefined, expect.anything());
expect(console.warn).not.toHaveBeenCalled();
});
});
describe("Sample apps", () => {
test("should support a simple counter app using local state", async () => {
const query = gql`
query GetCount {
count @client
lastCount # stored in db on server
}
`;
const increment = gql`
mutation Increment($amount: Int = 1) {
increment(amount: $amount) @client
}
`;
const decrement = gql`
mutation Decrement($amount: Int = 1) {
decrement(amount: $amount) @client
}
`;
const link = new ApolloLink((operation) => {
expect(operation.operationName).toBe("GetCount");
return of({ data: { lastCount: 1 } });
});
const localState = new LocalState();
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
localState,
});
const update = (
query: DocumentNode,
updater: (data: { count: number }, variables: { amount: number }) => any
): LocalState.Resolver<any, any, any, any> => {
return (_result: {}, variables: { amount: number }, { client }): null => {
const { cache } = client;
const read = client.readQuery<{ count: number }>({
query,
variables,
});
if (read) {
const data = updater(read, variables);
cache.writeQuery({ query, variables, data });
return data.count;
}
throw new Error("readQuery returned a falsy value");
};
};
localState.addResolvers({
Query: {
count: () => 0,
},
Mutation: {
increment: update(query, ({ count, ...rest }, { amount }) => ({
...rest,
count: count + amount,
})),
decrement: update(query, ({ count, ...rest }, { amount }) => ({
...rest,
count: count - amount,
})),
},
});
const stream = new ObservableStream(client.watchQuery({ query }));
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
await expect(stream).toEmitTypedValue({
data: { count: 0, lastCount: 1 },
dataState: "complete",
loading: false,
networkStatus: NetworkStatus.ready,
partial: false,
});
await expect(
client.mutate({ mutation: increment, variables: { amount: 2 } })
).resolves.toStrictEqualTyped({ data: { increment: 2 } });
await expect(stream).toEmitTypedValue({
data: { count: 2, lastCount: 1 },
dataState: "complete",
loading: false,
networkStatus: NetworkStatus.ready,
partial: false,
});
await client.mutate({ mutation: decrement, variables: { amount: 1 } });
await expect(stream).toEmitTypedValue({
data: { count: 1, lastCount: 1 },
dataState: "complete",
loading: false,
networkStatus: NetworkStatus.ready,
partial: false,
});
});
test("should support a simple todo app using local state", async () => {
const query = gql`
query GetTasks {
todos @client {
message
title
}
}
`;
const mutation = gql`
mutation AddTodo($message: String, $title: String) {
addTodo(message: $message, title: $title) @client
}
`;
const localState = new LocalState();
const client = new ApolloClient({
link: ApolloLink.empty(),
cache: new InMemoryCache(),
localState,
});
interface Todo {
title: string;
message: string;
__typename: string;
}
const update = (
query: DocumentNode,
updater: (todos: any, variables: Todo) => any
): LocalState.Resolver<any, any, any, any> => {
return (_result, variables: Todo, { client }): null => {
const { cache } = client;
const data = updater(client.readQuery({ query, variables }), variables);
cache.writeQuery({ query, variables, data });
return null;
};
};
localState.addResolvers({
Query: {
todos: () => [],
},
Mutation: {
addTodo: update(query, ({ todos }, { title, message }: Todo) => ({
todos: todos.concat([{ message, title, __typename: "Todo" }]),
})),
},
});
const stream = new ObservableStream(client.watchQuery<any>({ query }));
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
{
const { data } = await stream.takeNext();
expect(data).toEqual({ todos: [] });
}
await expect(
client.mutate({
mutation,
variables: {
title: "Apollo Client 2.0",
message: "ship it",
},
})
).resolves.toStrictEqualTyped({ data: { addTodo: null } });
{
const { data } = await stream.takeNext();
expect(data.todos).toEqual([
{
title: "Apollo Client 2.0",
message: "ship it",
__typename: "Todo",
},
]);
}
});
});
describe("Combining client and server state/operations", () => {
test("should merge remote and local state", async () => {
const query = gql`
query list {
list(name: "my list") {
items {
id
name
isDone
isSelected @client
}
}
}
`;
const data = {
list: {
__typename: "List",
items: [
{ __typename: "ListItem", id: 1, name: "first", isDone: true },
{ __typename: "ListItem", id: 2, name: "second", isDone: false },
],
},
};
const link = new ApolloLink(() => of({ data }).pipe(delay(20)));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
localState: new LocalState({
resolvers: {
Mutation: {
toggleItem: async (_, { id }, { client }) => {
const { cache } = client;
id = `ListItem:${id}`;
const fragment = gql`
fragment item on ListItem {
__typename
isSelected
}
`;
const previous = cache.readFragment<any>({ fragment, id });
const data = {
...previous,
isSelected: !previous.isSelected,
};
cache.writeFragment({
id,
fragment,
data,
});
return data;
},
},
ListItem: {
isSelected(source) {
expect(source.name).toBeDefined();
// List items default to an unselected state
return false;
},
},
},
}),
});
const observer = client.watchQuery({ query });
const stream = new ObservableStream(observer);
await expect(stream).toEmitTypedValue({
data: undefined,
dataState: "empty",
loading: true,
networkStatus: NetworkStatus.loading,
partial: true,
});
{
const response = await stream.takeNext();
const initial = { ...data };
initial.list.items = initial.list.items.map((x) => ({
...x,
isSelected: false,
}));
expect(response.data).toStrictEqualTyped(initial);
}
await client.mutate({
mutation: gql`
mutation SelectItem($id: Int!) {
toggleItem(id: $id) @client
}
`,
variables: { id: 1 },
});
{
const response = await stream.takeNext();
expect((response.data as any).list.items[0].isSelected).toBe(true);
expect((response.data as any).list.items[1].isSelected).toBe(false);
}
});
test("query resolves with loading: false if subsequent responses contain the same data", async () => {
const request = {
query: gql`
query people($id: Int) {
people(id: $id) {
id
name
}
}
`,
variables: {
id: 1,
},
};
const PersonType = new GraphQLObjectType({
name: "Person",
fields: {
id: { type: GraphQLID },
name: { type: GraphQLString },
},
});
const peopleData = [
{ id: 1, name: "John Smith" },
{ id: 2, name: "Sara Smith" },
{ id: 3, name: "Budd Deey" },
];
const QueryType = new GraphQLObjectType({
name: "Query",
fields: {
people: {
type: PersonType,
args: {
id: {
type: GraphQLInt,
},
},
resolve: (_, { id }) => {
return peopleData.find((p) => p.id === id);