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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107 | 10x
10x
10x
469x
252x
252x
252x
252x
252x
252x
252x
252x
252x
252x
252x
252x
10x
70x
70x
70x
1x
69x
69x
69x
68x
68x
68x
68x
129x
129x
43x
43x
54x
129x
68x
68x
68x
68x
68x
61x
61x
61x
61x
61x
61x
5x
4x
4x
1x
61x
7x
7x
7x
7x
7x
61x
61x
5x
61x
10x
308x
308x
308x
308x
308x
245x
245x
245x
245x
308x
308x
308x
308x
308x
308x
308x
308x
308x
46x
46x
46x
308x
265x
35x
12x
23x
23x
21x
21x
21x
23x
23x
265x
262x
46x
10x
240x
240x
240x
925x
925x
188x
737x
737x
737x
737x
737x
737x
737x
737x
737x
436x
29x
29x
29x
29x
29x
407x
407x
407x
407x
332x
332x
332x
75x
75x
75x
75x
75x
407x
407x
9x
398x
407x
3x
407x
407x
407x
384x
384x
407x
10x
236x
236x
1x
235x
234x
60x
60x
234x
103x
234x
234x
10x
76x
76x
1x
75x
2x
73x
2x
71x
71x
71x
71x
71x
71x
71x
61x
61x
9x
9x
71x
10x
317x
317x
317x
10x
185x
185x
185x
10x
244x
244x
244x
10x
308x
308x
308x
56x
308x
716x
716x
716x
514x
514x
379x
716x
716x
308x
10x
336x
10x
328x
10x
174x
174x
174x
121x
121x
121x
10x
117x
117x
117x
117x
117x
117x
87x
105x
10x
12x
12x
6x
6x
12x
12x
11x
11x
9x
12x
12x
12x
12x
12x
12x
12x
3x
9x
9x
6x
9x
12x
12x
10x
240x
240x
25x
240x
10x
7x
7x
7x
7x
7x
7x
7x
8x
8x
7x
10x
10x
10x
11x
11x
2x
2x
2x
7x
8x
5x
5x
5x
10x
185x
185x
10x
185x
10x
29x
29x
29x
24x
5x
5x
5x
5x
2x
3x
10x
10x
10x
10x
10x
10x
10x
10x
10x
974x
974x
974x
1568x
481x
1087x
943x
943x
10x
265x
265x
265x
265x
265x
265x
265x
265x
255x
255x
248x
248x
2x
2x
246x
246x
246x
253x
12x
12x
241x
5x
241x
5x
236x
236x
12x
235x
235x
265x
10x
4x
4x
4x
1x
1x
3x
2x
2x
2x
10x
308x
308x
308x
10x
6337x
10x
4089x
4089x
4089x
10x
1740x
1740x
14x
10x
| import {
execute,
ApolloLink,
Operation as Request,
FetchResult,
} from 'apollo-link-core';
import { ExecutionResult, DocumentNode } from 'graphql';
import { print } from 'graphql/language/printer';
import Deduplicator from 'apollo-link-dedup';
import { DiffResult } from 'apollo-cache-core';
import {
assign,
getDefaultValues,
getMutationDefinition,
getOperationDefinition,
getOperationName,
getQueryDefinition,
isProduction,
maybeDeepFreeze,
} from 'apollo-utilities';
import { QueryScheduler } from '../scheduler/scheduler';
import { isApolloError, ApolloError } from '../errors/ApolloError';
import { Observer, Subscription, Observable } from '../util/Observable';
import { QueryWithUpdater, DataStore } from '../data/store';
import { MutationStore } from '../data/mutations';
import { QueryStore, QueryStoreValue } from '../data/queries';
import {
WatchQueryOptions,
SubscriptionOptions,
MutationOptions,
} from './watchQueryOptions';
import { ObservableQuery } from './ObservableQuery';
import { NetworkStatus, isNetworkRequestInFlight } from './networkStatus';
import { QueryListener, ApolloQueryResult, FetchType } from './types';
export interface QueryInfo {
listeners: QueryListener[];
invalidated: boolean;
newData: ApolloQueryResult<any> | null;
document: DocumentNode | null;
lastRequestId: number | null;
// A map going from queryId to an observer for a query issued by watchQuery. We use
// these to keep track of queries that are inflight and error on the observers associated
// with them in case of some destabalizing action (e.g. reset of the Apollo store).
observableQuery: ObservableQuery<any> | null;
cancel?: (() => void);
}
const defaultQueryInfo = {
listeners: [],
invalidated: false,
document: null,
newData: null,
lastRequestId: null,
observableQuery: null,
};
export class QueryManager {
public scheduler: QueryScheduler;
public link: ApolloLink;
public mutationStore: MutationStore = new MutationStore();
public queryStore: QueryStore = new QueryStore();
public dataStore: DataStore;
private deduplicator: ApolloLink;
private queryDeduplication: boolean;
private onBroadcast: () => void;
// XXX merge with ObservableQuery but that needs to be expanded to support mutations and
// subscriptions as well
private queries: Map<string, QueryInfo> = new Map();
private idCounter = 1; // let's not start at zero to avoid pain with bad checks
// A map going from a requestId to a promise that has not yet been resolved. We use this to keep
// track of queries that are inflight and reject them in case some
// destabalizing action occurs (e.g. reset of the Apollo store).
private fetchQueryPromises: {
[requestId: string]: {
promise: Promise<ApolloQueryResult<any>>;
resolve: (result: ApolloQueryResult<any>) => void;
reject: (error: Error) => void;
};
} = {};I
// A map going from the name of a query to an observer issued for it by watchQuery. This is
// generally used to refetches for refetchQueries and to update mutation results through
// updateQueries.
private queryIdsByName: { [queryName: string]: string[] } = {};
constructor({
link,
queryDeduplication = false,
store,
onBroadcast = () => undefined,
ssrMode = false,
}: {
link: ApolloLink;
queryDeduplication?: boolean;
store: DataStore;
onBroadcast?: () => void;
ssrMode: boolean;
}) {
this.link = link;
this.deduplicator = ApolloLink.from([new Deduplicator(), link]);
this.queryDeduplication = queryDeduplication;
this.dataStore = store;
this.onBroadcast = onBroadcast;
this.scheduler = new QueryScheduler({ queryManager: this, ssrMode });
}
public mutate<T>({
mutation,
variables,
optimisticResponse,
updateQueries: updateQueriesByName,
refetchQueries = [],
update: updateWithProxyFn,
errorPolicy = 'ignore',
}: MutationOptions): Promise<FetchResult<T>> {
if (!mutation) {
throw new Error(
'mutation option is required. You must specify your GraphQL document in the mutation option.',
);
}
const mutationId = this.generateQueryId();
mutation = this.dataStore.getCache().transformDocument(mutation);
variables = assign(
{},
getDefaultValues(getMutationDefinition(mutation)),
variables,
);
const mutationString = print(mutation);
const request = {
query: mutation,
variables,
operationName: getOperationName(mutation) || undefined,
} as Request;
this.setQuery(mutationId, () => ({ document: mutation }));
// Create a map of update queries by id to the query instead of by name.
const generateUpdateQueriesInfo: () => {
[queryId: string]: QueryWithUpdater;
} = () => {
const ret: { [queryId: string]: QueryWithUpdater } = {};
if (updateQueriesByName) {
Object.keys(updateQueriesByName).forEach(queryName =>
(this.queryIdsByName[queryName] || []).forEach(queryId => {
ret[queryId] = {
updater: updateQueriesByName[queryName],
query: this.queryStore.get(queryId),
};
}),
);
}
return ret;
};
this.mutationStore.initMutation(mutationId, mutationString, variables);
this.dataStore.markMutationInit({
mutationId,
document: mutation,
variables: variables || {},
updateQueries: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
optimisticResponse,
});
this.broadcastQueries();
return new Promise((resolve, reject) => {
let storeResult: FetchResult<T> | null;
execute(this.link, request).subscribe({
next: (result: ExecutionResult) => {
if (result.errors && errorPolicy === 'none') {
const error = new ApolloError({
graphQLErrors: result.errors,
});
this.mutationStore.markMutationError(mutationId, error);
this.dataStore.markMutationComplete(mutationId);
this.broadcastQueries();
this.setQuery(mutationId, () => ({ document: undefined }));
reject(error);
return;
}
this.mutationStore.markMutationResult(mutationId);
this.dataStore.markMutationResult({
mutationId,
result,
document: mutation,
variables: variables || {},
updateQueries: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
});
this.dataStore.markMutationComplete(mutationId);
this.broadcastQueries();
refetchQueries.forEach(refetchQuery => {
if (typeof refetchQuery === 'string') {
this.refetchQueryByName(refetchQuery);
return;
}
this.query({
query: refetchQuery.query,
variables: refetchQuery.variables,
fetchPolicy: 'network-only',
});
});
storeResult = result as FetchResult<T>;
},
error: (err: Error) => {
this.mutationStore.markMutationError(mutationId, err);
thIis.dataStore.markMutationComplete(mutationId);
this.broadcastQueries();
this.setQuery(mutationId, () => ({ document: undefined }));
reject(
new ApolloError({
networkError: err,
}),
);
},
complete: () => {
this.setQuery(mutationId, () => ({ document: undefined }));
if (errorPolicy === 'ignore' && storeResult && storeResult.errors) {
delete storeResult.errors;
}
resolve(storeResult as FetchResult<T>);
},
});
});
}
public fetchQuery<T>(
queryId: string,E
options: WatchQueryOptions,
fetchType?: FetchType,
// This allows us to track if this is a query spawned by a `fetchMore`
// call for another query. We need this data to compute the `fetchMore`
// network status for the query this is fetching for.
fetchMoreForQueryId?: string,
): Promise<FetchResult<T>> {
const {
variables = {},
metadata = null,
fetchPolicy = 'cache-first', // cache-first is the default fetch policy.
} = options;
const query = this.dataStore.getCache().transformDocument(options.query);
let storeResult: any;
let needToFetch: boolean = fetchPolicy === 'network-only';
// If this is not a force fetch, we want to diff the query against the
// store before we fetch it from the network interface.
// TODO we hit the cache even if the policy is network-first. This could be unnecessary if the network is up.
if (fetchType !== FetchType.refetch && fetchPolicy !== 'network-only') {
const { isMissing, result } = this.dataStore.getCache().diffQuery({
query,
variables,
returnPartialData: true,
optimistic: false,
});
// If we're in here, only fetch if we have missing fields
needToFetch = isMissinIg || fetchPolicy === 'cache-and-network';
storeResult = result;
}
const shouldFetch =
needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby';
const requestId = this.generateRequestId();
// Initialize query in store with unique requestId
this.setQuery(queryId, () => ({
document: query,
lastRequestId: requestId,
}));
// set up a watcher to listen to cache updates
this.updateQueryWatch(queryId, options);
this.queryStore.initQuery({
queryId,
queryString: print(query),
document: query,
storePreviousVariables: shouldFetch,
variables,
isPoll: fetchType === FetchType.poll,
isRefetch: fetchType === FetchType.refetch,
metadata,
fetchMoreForQueryId,
});
// XXX can we batch query updates here?
this.invalidate(true, queryId, fetchMoreForQueryId);
this.broadcastQueries();
// If there is no part of the query we need to fetch from the server (or,
// fetchPolicy is cache-only), we just write the store result as the final result.
const shouldDispatchClientResult =
!shouldFetch || fetchPolicy === 'cache-and-network';
if (shouldDispatchClEientResult) {
this.queryStore.markQueryResultClient(queryId, !shouldFetch);
this.invalidate(true, queryId, fetchMoreForQueryId);
this.broadcastQueries();
}
if (shouldFetch) {
const networkResult = this.fetchRequest({
requestId,
queryId,
document: query,
options,
fetchMoreForQueryId,
}).catch(error => {
// This is for the benefit of `refetch` promises, which currently don't get their errors
// through the store like watchQuery observers do
if (isApolloError(error)) {
throw error;
} else {
const { lastRequestId } = this.getQuery(queryId);
if (requestId >= (lastRequestId || 1)) {
this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId);
this.invalidate(true, queryId, fetchMoreForQueryId);
this.broadcastQueries();
}
this.removeFetchQueryPromise(requestId);
throw new ApolloError({
networkError: error,
});
}
});
if (fetchPolicy !== 'cache-and-network') {
return networkResult;
}
}
// If we have no query to send to the server, we should return the result
// found within the store.
return Promise.resolve<ExecutionResult>({ data: storeResult });
}
// Returns a query listener that will update the given observer based on the
// results (or lack thereof) for a particular query.
public queryListenerForObserver<T>(
queryId: string,
options: WatchQueryOptions,
observer: Observer<ApolloQueryResult<T>>,
): QueryListener {
let previouslyHadError: boolean = false;
return (queryStoreValue: QueryStoreValue, newData?: DiffResult<T>) => {
// we're going to take a look at the data, so the query is no longer invalidated
this.invalidate(false, queryId);
// The query store value can be undefined in the event of a store
// reset.
if (!queryStoreValue) return;
//I XXX This is to fix a strange race condition that was the root cause of react-apollo/#170
// queryStoreValue was sometimes the old queryStoreValue and not what's currently in the store.
queryStoreValue = this.queryStore.get(queryId);
I
const { observableQuery } = this.getQuery(queryId);
const fetchPolicy = observableQuery
? observableQuery.options.fetchPolicy
: options.fetchPolicy;
const errorPolicy = observableQuery
? observableQuery.options.errorPolicy
: options.errorPolicy;
// don't watch the store for queries on standby
if (fetchPolicy === 'standby') return;
const lastResult = observableQuery
? observableQuery.getLastResult()
: null;
const shouldNotifyIfLoading =
queryStoreValue.previousVariables ||
fetchPolicy === 'cache-only' ||
fetchPolicy === 'cache-and-network';
const networkStatusChanged =
lastResult &&
queryStoreValue.networkStatus !== lastResult.networkStatus;
if (
!isNetworkRequestInFlight(queryStoreValue.networkStatus) ||
(networkStatusChanged && options.notifyOnNetworkStatusChange) ||
shouldNotifyIfLoading
) {
// If we have either a GraphQL error or a network error, we create
// an error and tell the observer about it.
if (
((!errorPolicy || errorPolicy === 'none') &&
queryStoreValue.graphQLErrors &&
queryStoreValue.graphQLErrors.length > 0) ||
queryStoreValue.networkError
) {
const apolloError = new ApolloError({
graphQLErrors: queryStoreValue.graphQLErrors,
networkError: queryStoreValue.networkError,
});
previouslyHadError = true;
if (observer.error) {
try {
observer.error(apolloError);
} catch (e) {
// Throw error outside this control flow to avoid breaking Apollo's state
setTimeout(() => {
throw e;
}, 0);
}
} else {
// Throw error outside this control flow to avoid breaking Apollo's state
setTimeout(() => {
throw apolloError;
}, 0);
if (!isProduction()) {
/* tslint:disable-next-line */
console.info(
'An unhandled error was thrown because no error handler is registered ' +
'for the query ' +
queryStoreValue.queryString,
);
}
}
} else {
try {
let data: any;
let isMissing: boolean;
if (newData) {
// clear out the latest new data, since we're now using it
this.setQuery(queryId, () => ({ newData: null }));
data = newData.result;
isMissing = newData.isMissing ? newData.isMissing : false;
} else {
if (
lastResult &&
lastResult.data &&
queryStoreValue.previousVariables === queryStoreValue.variables
) {
data = lastResult.data;
I isMissing = false;
} else {
const { document } = this.getQuery(queryId);
const readResult = this.dataStore.getCache().diffQuery({
query: document as DocumentNode,
variables:
queryStoreValue.previousVariables ||
queryStoreValue.variables,
optimistic: true,
});
data = readResult.result;
isMissing = readResult.isMissing;
}
}
let resultFromStore: ApolloQueryResult<T>;
// If there is some data missing and the user has told us that they
// do not tolerate partial data then we want to return the previous
// result and mark it as stale.
if (isMissing && fetchPolicy !== 'cache-only') {
resultFromStore = {
data: lastResult && lastResult.data,
loading: isNetworkRequestInFlight(
queryStoreValue.networkStatus,
),
networkStatus: queryStoreValue.networkStatus,
stale: true,
};
} else {
resultFromStore = {
data,
loading: isNetworkRequestInFlight(
queryStoreValue.networkStatus,
),
networkStatus: queryStoreValue.networkStatus,
stale: false,
};
}
// if the query wants updates on errors we need to add it to the result
if (
errorPolicy === 'all' &&
queryStoreValue.graphQLErrors &&
queryStoreValue.graphQLErrors.length > 0
) {
resultFromStore.errors = queryStoreValue.graphQLErrors;
}
if (observer.next) {
const isDifferentResult = !(
lastResult &&
resultFromStore &&
lastResult.networkStatus === resultFromStore.networkStatus &&
lastResult.stale === resultFromStore.stale &&
// We can do a strict equality check here because we include a `previousResult`
// with `readQueryFromStore`. So if the results are the same they will be
// referentially equal.
lastResult.data === resultFromStore.data
);
if (isDifferentResult || previouslyHadError) {
try {
observer.next(maybeDeepFreeze(resultFromStore));
} catch (e) {
// Throw eError outside this control flow to avoid breaking Apollo's state
setTimeout(() => {
throw e;
}, 0);
}
}
}E
previouslyHadError = false;
} catch (error) {
previouslyHadError = true;
if (observer.error) {
observer.error(
new ApolloError({
networkError: error,
}),
);E
}
return;
}
}
}
};
}
// The shouldSubscribe option is a temporary fix that tells us whether watchQuery was called
// directly (i.e. through ApolloClient) or through the query method within QueryManager.
// Currently, the query method uses watchQuery in order to handle non-network errors correctly
// but we don't want to keep track observables issued for the query method since those aren't
// supposed to be refetched in the event of a store reset. Once we unify error handling for
// network errors and non-network errors, the shouldSubscribe option will go away.
public watchQuery<T>(
options: WatchQueryOptions,
shouldSubscribe = true,
): ObservableQuery<T> {
if (options.fetchPolicy === 'standby') {
throw Inew Error(
'client.watchQuery cannot be called with fetchPolicy set to "standby"',
);
}
// get errors synchronously
const queryDefinition = getQueryDefinition(options.query);
// assign variable default values if supplied
if (
queryDefinition.variableDefinitions &&
queryDefinition.variableDefinitions.length
) {
const defaultValues = getDefaultValues(queryDefinition);
options.variables = assign({}, defaultValues, options.variables);
}
if (typeof options.notifyOnNetworkStatusChange === 'undefined') {
options.notifyOnNetworkStatusChange = false;
}E
let tranIsformedOptions = { ...options } as WatchQueryOptions;
return new ObservableQuery<T>({
scheduler: this.scheduler,
options: transformedOptions,
shouldSubscribe: shouldSubscribe,
});
}
public query<T>(options: WatchQueryOptions): Promise<ApolloQueryResult<T>> {
if (!options.query) {
throw new Error(
'query option is required. You must specify your GraphQL document in the query option.',
);
}
if (options.query.kind !== 'Document') {
throw new Error('You must wrap the query string in a "gql" tag.');
}
if ((options as any).returnPartialData) {
throw new Error('returnPartialData option only supported on watchQuery.');
}
if ((options as any).pollInterval) {
throw new Error('pollInterval option only supported on watchQuery.');
}
if (typeof options.notifyOnNetworkStatusChange !== 'undefined') {
throw new Error(
'Cannot call "query" with "notifyOnNetworkStatusChange" option. Only "watchQuery" has that option.',
);
}
options.notifyOnNetworkStatusChange = false;
const requestId = this.idCounter;
const resPromise = new Promise<ApolloQueryResult<T>>((resolve, reject) => {
this.addFetchQueryPromise<T>(requestId, resPromise, resolve, reject);
return this.watchQuery<T>(options, false)
.result()
.then(result => {
this.removeFetchQueryPromise(requestId);
resolve(result);
})
.catch(error => {
this.removeFetchQueryPromise(requestId);
reject(error);
});
});
return resPromise;
}
public generateQueryId() {
const queryId = this.idCounter.toString();
this.idCounter++;
return queryId;
}
public stopQueryInStore(queryId: string) {
this.queryStore.stopQuery(queryId);
this.invalidate(true, queryId);
this.broadcastQueries();
}
public addQueryListener(queryId: string, listener: QueryListener) {
this.setQuery(queryId, ({ listeners = [] }) => ({
listeners: [...listeners, listener],
invalidate: false,
}));
}
public updateQueryWatch(queryId: string, options: WatchQueryOptions) {
let { cancel, document } = this.getQuery(queryId);
if (cancel) cancel();
cancel = this.dataStore.getCache().watch({
query: document as DocumentNode,
variables: options.variables,
optimistic: true,
previousResult: () => {
let previousResult = null;
const { observableQuery } = this.getQuery(queryId);
if (observableQuery) {
const lastResult = observableQuery.getLastResult();
if (lastResult) {
previousResult = lastResult.data;
}
}
return previousResult;
},
callback: (newData: ApolloQueryResult<any>) => {
this.setQuery(queryId, () => ({ invalidated: true, newData }));
},
});
this.setQuery(queryId, () => ({ cancel }));
}
// Adds a promise to this.fetchQueryPromises for a given request ID.
public addFetchQueryPromise<T>(
requestId: number,
promise: Promise<ApolloQueryResult<T>>,
resolve: (result: ApolloQueryResult<T>) => void,
reject: (error: Error) => void,
) {
this.fetchQueryPromises[requestId.toString()] = {
promise,
resolve,
reject,
};
}
// Removes the promise in this.fetchQueryPromises for a particular request ID.
public removeFetchQueryPromise(requestId: number) {
delete this.fetchQueryPromises[requestId.toString()];
}
// Adds an ObservableQuery to this.observableQueries and to this.observableQueriesByName.
public addObservableQuery<T>(
queryId: string,
observableQuery: ObservableQuery<T>,
) {
this.setQuery(queryId, () => ({ observableQuery }));
// Insert the ObservableQuery into this.observableQueriesByName if the query has a name
const queryDef = getQueryDefinition(observableQuery.options.query);
if (queryDef.name && queryDef.name.value) {
const queryName = queryDef.name.value;
// XXX we may we want to warn the user about query name conflicts in the future
this.queryIdsByName[queryName] = this.queryIdsByName[queryName] || [];
this.queryIdsByName[queryName].push(observableQuery.queryId);
}
}
public removeObservableQuery(queryId: string) {
const { observableQuery } = this.getQuery(queryId);
if (!observableQuery) return;
const definition = getQueryDefinition(observableQuery.options.query);
const queryName = definition.name ? definition.name.value : null;
this.setQuery(queryId, () => ({ observableQuery: null }));
if (queryName) {
this.queryIdsByName[queryName] = this.queryIdsByName[
queryName
].filter(val => {
return !(observableQuery.queryId === val);
});
}
}
public resetStore(): Promise<ApolloQueryResult<any>[]> {
// Before we have sent the reset action to the store,
// we can no longer rely on the results returned by in-flight
// requests since these may depend on values that previously existed
// in the data portion of the store. So, we cancel the promises and observers
// that we have issued so far and not yet resolved (in the case of
// queries).
Object.keys(this.fetchQueryPromises).forEach(key => {
const { reject } = this.fetchQueryPromises[key];
reject(new Error('Store reset while query was in flight.'));
});
const resetIds: string[] = [];
this.queries.forEach(({ observableQuery }, queryId) => {
if (observableQuery) resetIds.push(queryId);
});
this.queryStore.reset(resetIds);
this.mutationStore.reset();
const dataStoreReset = this.dataStore.reset();
// Similarly, we have to have to refetch each of the queries currently being
// observed. We refetch instead of error'ing on these since the assumption is that
// resetting the store doesn't eliminate the need for the queries currently being
// watched. If there is an existing query in flight when the store is reset,
// the promise for it will be rejected and its results will not be written to the
// store.
const observableQueryPromises: Promise<ApolloQueryResult<any>>[] = [];
this.queries.forEach(({ observableQuery }, queryId) => {
if (!observableQuery) return;
const fetchPolicy = observableQuery.options.fetchPolicy;
if (fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby') {
observableQueryPromises.push(observableQuery.refetch());
}
this.invalidate(true, queryId);
});
this.broadcastQueries();
return dataStoreReset.then(() => Promise.all(observableQueryPromises));
}
public startQuery<T>(
queryId: string,
options: WatchQueryOptions,
listener: QueryListener,
) {
this.addQueryListener(queryId, listener);
this.fetchQuery<T>(queryId, options)
// `fetchQuery` returns a Promise. In case of a failure it should be caucht or else the
// console will show an `Uncaught (in promise)` message. Ignore the error for now.
.catch(() => undefined);
return queryId;
}
public startGraphQLSubscription(
options: SubscriptionOptions,
): Observable<any> {
const { query } = options;
let transformedDoc = this.dataStore.getCache().transformDocument(query);
const variables = assign(
{},
getDefaultValues(getOperationDefinition(query)),
options.variables,
);
const request: Request = {
query: transformedDoc,
variables,
operationName: getOperationName(transformedDoc) || undefined,
};
let sub: Subscription;
let observers: Observer<any>[] = [];
return new Observable(observer => {
observers.push(observer);
// If this is the first observer, actually initiate the network subscription
if (observers.length === 1) {
const handler = {
next: (result: FetchResult) => {
this.dataStore.markSubscriptionResult(
result,
transformedDoc,
variables,
);
this.broadcastQueries();
// It's slightly awkward that the data for subscriptions doesn't come from the store.
observers.forEach(obs => {
if (obs.next) obs.next(result);
});
},
error: (error: Error) => {
observers.forEach(obs => {
if (obs.error) obs.error(error);
});
},
};
sub = execute(this.link, request).subscribe(handler);
}
return () => {
observers = observers.filter(obs => obs !== observer);
// If we removed the last observer, tear down the network subscription
if (observers.length === 0 && sub) {
sub.unsubscribe();
}
};
});
}
public stopQuery(queryId: string) {
this.stopQueryInStore(queryId);
this.removeQuery(queryId);
}
public removeQuery(queryId: string) {
this.queries.delete(queryId);
}
public getCurrentQueryResult<T>(observableQuery: ObservableQuery<T>) {
const { variables, query } = observableQuery.options;
const lastResult = observableQuery.getLastResult();
if (lastResult && lastResult.data) {
return maybeDeepFreeze({ data: lastResult.data, partial: false });
} else {
const { newData } = this.getQuery(observableQuery.queryId);
if (newData) {
return maybeDeepFreeze({ data: newData.data, partial: false });
} else {
try {
// the query is brand new, so we read from the store to see if anything is there
const diffResult = this.dataStore.getCache().read({
query,
variables,
optimistic: true,
});
return maybeDeepFreeze({ data: diffResult, partial: false });
} catch (e) {
return maybeDeepFreeze({ data: {}, partial: true });
}
}
}
}
public getQueryWithPreviousResult<T>(
queryIdOrObservable: string | ObservableQuery<T>,
) {
let observableQuery: ObservableQuery<T>;
if (typeof queryIdOrObservable === 'string') {
const { observableQuery: foundObserveableQuery } = this.getQuery(
queryIdOrObservable,
);
if (!foundObserveableQuery) {
throw new Error(
`ObservableQuery with this id doesn't exist: ${queryIdOrObservable}`,
);
}
observableQuery = foundObserveableQuery;
} else {
observableQuery = queryIdOrObservable;
}
const { variables, query } = observableQuery.options;
const { data } = this.getCurrentQueryResult(observableQuery);
return {
previousResult: data,
variables,
document: query,
};
}
public broadcastQueries() {
this.onBroadcast();
this.queries.forEach((info, id) => {
if (!info.invalidated || !info.listeners) return;
info.listeners
.filter((x: QueryListener) => !!x)
.forEach((listener: QueryListener) => {
// it's possible for the listener to be undefined if the query is being stopped
// See here for more detail: https://github.com/apollostack/apollo-client/issues/231
listener(this.queryStore.get(id), info.newData);
});
});
}
// Takes a request id, query id, a query document and information associated with the query
// and send it to the network interface. Returns
// a promise for the result associated with that request.
private fetchRequest<T>({
requestId,
queryId,
document,
options,
fetchMoreForQueryId,
}: {
requestId: number;
queryId: string;
document: DocumentNode;
options: WatchQueryOptions;
fetchMoreForQueryId?: string;
}): Promise<ExecutionResult> {
const { variables, context, errorPolicy = 'none' } = options;
const request = {
query: document,
variables,
operationName: getOperationName(document) || undefined,
context: context || {},
};
request.context.forceFetch = !this.queryDeduplication;
let resultFromStore: any;
let errorsFromStore: any;
const retPromise = new Promise<ApolloQueryResult<T>>((resolve, reject) => {
this.addFetchQueryPromise<T>(requestId, retPromise, resolve, reject);
execute(this.deduplicator, request).subscribe({
next: (result: ExecutionResult) => {
// default the lastRequestId to 1
const { lastRequestId } = this.getQuery(queryId);
if (requestId >= (lastRequestId || 1)) {
try {
this.dataStore.markQueryResult(
result,
document,
variables,
fetchMoreForQueryId,
errorPolicy === 'ignore',
);
} catch (e) {
reject(e);
return;
}
this.queryStore.markQueryResult(
queryId,
result,
fetchMoreForQueryId,
);
this.invalidate(true, queryId, fetchMoreForQueryId);
this.broadcastQueries();
}
if (result.errors && errorPolicy === 'none') {
reject(
new ApolloError({
graphQLErrors: result.errors,
}),
);
return;
} else if (errorPolicy === 'all') {
errorsFromStore = result.errors;
}
if (fetchMoreForQueryId) {
// We don't write fetchMore results to the store because this would overwrite
// the original result in case an @connection directive is used.
resultFromStore = result.data;
} else {
try {
// ensure result is combined with data already in store
resultFromStore = this.dataStore.getCache().read({
variables,
query: document,
optimistic: false,
});
// this will throw an error if there are missing fields in
// the results which can happen with errors from the server.
// tslint:disable-next-line
} catch (e) {}
}
},
error: (error: ApolloError) => {
reject(error);
},
complete: () => {
this.removeFetchQueryPromise(requestId);
resolve({
data: resultFromStore,
errors: errorsFromStore,
loading: false,
networkStatus: NetworkStatus.ready,
stale: false,
});
},
});
});
return retPromise;
}
// Refetches a query given that query's name. Refetches
// all ObservableQuery instances associated with the query name.
private refetchQueryByName(queryName: string) {
const refetchedQueries = this.queryIdsByName[queryName];
// Warn if the query named does not exist (misnamed, or merely not yet fetched)
if (refetchedQueries === undefined) {
console.warn(
`Warning: unknown query with name ${queryName} asked to refetch`,
);
return;
} else {
return Promise.all(
refetchedQueries
.map(id => this.getQuery(id).observableQuery)
.filter(x => !!x)
.map((x: ObservableQuery<any>) => x.refetch()),
);
}
}
private generateRequestId() {
const requestId = this.idCounter;
this.idCounter++;
return requestId;
}
private getQuery(queryId: string) {
return this.queries.get(queryId) || { ...defaultQueryInfo };
}
private setQuery(queryId: string, updater: (prev: QueryInfo) => any) {
const prev = this.getQuery(queryId);
const newInfo = { ...prev, ...updater(prev) };
this.queries.set(queryId, newInfo);
}
private invalidate(
invalidated: boolean,
queryId: string,
fetchMoreForQueryId?: string,
) {
this.setQuery(queryId, () => ({ invalidated }));
if (fetchMoreForQueryId) {
this.setQuery(fetchMoreForQueryId, () => ({ invalidated }));
}
}
}
|