-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
QueryManager.ts
1352 lines (1159 loc) · 42.8 KB
/
QueryManager.ts
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 {
NetworkInterface,
SubscriptionNetworkInterface,
Request,
} from '../transport/networkInterface';
import { Deduplicator } from '../transport/Deduplicator';
import { isEqual } from '../util/isEqual';
import { assign } from '../util/assign';
import {
QueryListener,
ApolloQueryResult,
ApolloExecutionResult,
PureQueryOptions,
FetchType,
} from './types';
import { QueryStore, QueryStoreValue } from '../queries/store';
import {
NetworkStatus,
isNetworkRequestInFlight,
} from '../queries/networkStatus';
import {
ApolloStore,
Store,
getDataWithOptimisticResults,
ApolloReducerConfig,
ApolloReducer,
} from '../store';
import {
checkDocument,
getQueryDefinition,
getOperationDefinition,
getOperationName,
getDefaultValues,
getMutationDefinition,
} from '../queries/getFromAST';
import { addTypenameToDocument } from '../queries/queryTransform';
import { NormalizedCache } from '../data/storeUtils';
import { createStoreReducer } from '../data/resultReducers';
import { DataProxy } from '../data/proxy';
import {
FragmentMatcherInterface,
HeuristicFragmentMatcher,
} from '../data/fragmentMatcher';
import { isProduction } from '../util/environment';
import maybeDeepFreeze from '../util/maybeDeepFreeze';
import {
ExecutionResult,
DocumentNode,
// TODO REFACTOR: do we still need this??
// We need to import this here to allow TypeScript to include it in the definition file even
// though we don't use it. https://github.com/Microsoft/TypeScript/issues/5711
// We need to disable the linter here because TSLint rightfully complains that this is unused.
/* tslint:disable */
SelectionSetNode,
/* tslint:enable */
} from 'graphql';
import { print } from 'graphql/language/printer';
import { readQueryFromStore, ReadQueryOptions } from '../data/readFromStore';
import { diffQueryAgainstStore } from '../data/readFromStore';
import { QueryWithUpdater } from '../actions';
import {
MutationQueryReducersMap,
MutationQueryReducer,
} from '../data/mutationResults';
import { MutationStore } from '../mutations/store';
import { QueryScheduler } from '../scheduler/scheduler';
import { ApolloStateSelector } from '../ApolloClient';
import { Observer, Subscription, Observable } from '../util/Observable';
import { tryFunctionOrLogError } from '../util/errorHandling';
import { isApolloError, ApolloError } from '../errors/ApolloError';
import { WatchQueryOptions, SubscriptionOptions } from './watchQueryOptions';
import { ObservableQuery } from './ObservableQuery';
export class QueryManager {
public static EMIT_REDUX_ACTIONS = true;
public pollingTimers: { [queryId: string]: any };
public scheduler: QueryScheduler;
public store: ApolloStore;
public networkInterface: NetworkInterface;
public ssrMode: boolean;
public mutationStore: MutationStore = new MutationStore();
public queryStore: QueryStore = new QueryStore();
private addTypename: boolean;
private deduplicator: Deduplicator;
private reduxRootSelector: ApolloStateSelector;
private reducerConfig: ApolloReducerConfig;
private queryDeduplication: boolean;
private fragmentMatcher: FragmentMatcherInterface;
// TODO REFACTOR collect all operation-related info in one place (e.g. all these maps)
// this should be combined with ObservableQuery, but that needs to be expanded to support
// mutations and subscriptions as well.
private queryListeners: { [queryId: string]: QueryListener[] };
private queryDocuments: { [queryId: string]: DocumentNode };
private idCounter = 1; // XXX 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;
};
};
// 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).
private observableQueries: {
[queryId: string]: {
observableQuery: ObservableQuery<any>;
};
};
// 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[] };
private lastRequestId: { [queryId: string]: number } = {};
private disableBroadcasting = false;
constructor({
networkInterface,
store,
reduxRootSelector,
reducerConfig = {},
fragmentMatcher,
addTypename = true,
queryDeduplication = false,
ssrMode = false,
}: {
networkInterface: NetworkInterface;
store: ApolloStore;
reduxRootSelector: ApolloStateSelector;
fragmentMatcher?: FragmentMatcherInterface;
reducerConfig?: ApolloReducerConfig;
addTypename?: boolean;
queryDeduplication?: boolean;
ssrMode?: boolean;
}) {
// XXX this might be the place to do introspection for inserting the `id` into the query? or
// is that the network interface?
this.networkInterface = networkInterface;
this.deduplicator = new Deduplicator(networkInterface);
this.store = store;
this.reduxRootSelector = reduxRootSelector;
this.reducerConfig = reducerConfig;
this.pollingTimers = {};
this.queryListeners = {};
this.queryDocuments = {};
this.addTypename = addTypename;
this.queryDeduplication = queryDeduplication;
this.ssrMode = ssrMode;
// XXX This logic is duplicated in ApolloClient.ts for two reasons:
// 1. we need it in ApolloClient.ts for readQuery and readFragment of the data proxy.
// 2. we need it here so we don't have to rewrite all the tests.
// in the longer term we should remove the need for 2 and move it to ApolloClient.ts only.
if (typeof fragmentMatcher === 'undefined') {
this.fragmentMatcher = new HeuristicFragmentMatcher();
} else {
this.fragmentMatcher = fragmentMatcher;
}
this.scheduler = new QueryScheduler({
queryManager: this,
});
this.fetchQueryPromises = {};
this.observableQueries = {};
this.queryIdsByName = {};
// this.store is usually the fake store we get from the Redux middleware API
// XXX for tests, we sometimes pass in a real Redux store into the QueryManager
if ((this.store as any)['subscribe']) {
let currentStoreData: any;
(this.store as any)['subscribe'](() => {
let previousStoreData = currentStoreData || {};
const previousStoreHasData = Object.keys(previousStoreData).length;
currentStoreData = this.getApolloState();
if (
isEqual(previousStoreData, currentStoreData) &&
previousStoreHasData
) {
return;
}
this.broadcastQueries();
});
}
}
// Called from middleware
public broadcastNewStore(store: any) {
this.broadcastQueries();
}
public mutate<T>({
mutation,
variables,
optimisticResponse,
updateQueries: updateQueriesByName,
refetchQueries = [],
update: updateWithProxyFn,
}: {
mutation: DocumentNode;
variables?: Object;
optimisticResponse?: Object | Function;
updateQueries?: MutationQueryReducersMap<T>;
refetchQueries?: string[] | PureQueryOptions[];
update?: (proxy: DataProxy, mutationResult: Object) => void;
}): Promise<ApolloExecutionResult<T>> {
if (!mutation) {
throw new Error(
'mutation option is required. You must specify your GraphQL document in the mutation option.',
);
}
const mutationId = this.generateQueryId();
if (this.addTypename) {
mutation = addTypenameToDocument(mutation);
}
variables = assign(
{},
getDefaultValues(getMutationDefinition(mutation)),
variables,
);
const mutationString = print(mutation);
const request = {
query: mutation,
variables,
operationName: getOperationName(mutation),
} as Request;
this.queryDocuments[mutationId] = 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] = {
reducer: updateQueriesByName[queryName],
query: this.queryStore.get(queryId),
};
}),
);
}
return ret;
};
this.store.dispatch({
type: 'APOLLO_MUTATION_INIT',
mutationString,
mutation,
variables: variables || {},
operationName: getOperationName(mutation),
mutationId,
optimisticResponse,
extraReducers: this.getExtraReducers(),
updateQueries: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
});
this.mutationStore.initMutation(mutationId, mutationString, variables);
return new Promise<ApolloExecutionResult<T>>((resolve, reject) => {
this.networkInterface
.query(request)
.then(result => {
if (result.errors) {
const error = new ApolloError({
graphQLErrors: result.errors,
});
this.store.dispatch({
type: 'APOLLO_MUTATION_ERROR',
error,
mutationId,
});
this.mutationStore.markMutationError(mutationId, error);
delete this.queryDocuments[mutationId];
reject(error);
return;
}
this.store.dispatch({
type: 'APOLLO_MUTATION_RESULT',
result,
mutationId,
document: mutation,
operationName: getOperationName(mutation),
variables: variables || {},
extraReducers: this.getExtraReducers(),
updateQueries: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
});
this.mutationStore.markMutationResult(mutationId);
// If there was an error in our reducers, reject this promise!
const { reducerError } = this.getApolloState();
if (reducerError && reducerError.mutationId === mutationId) {
reject(reducerError.error);
return;
}
if (typeof refetchQueries[0] === 'string') {
(refetchQueries as string[]).forEach(name => {
this.refetchQueryByName(name);
});
} else {
(refetchQueries as PureQueryOptions[]).forEach(pureQuery => {
this.query({
query: pureQuery.query,
variables: pureQuery.variables,
fetchPolicy: 'network-only',
});
});
}
delete this.queryDocuments[mutationId];
resolve(result as ApolloExecutionResult<T>);
})
.catch(err => {
this.store.dispatch({
type: 'APOLLO_MUTATION_ERROR',
error: err,
mutationId,
});
delete this.queryDocuments[mutationId];
reject(
new ApolloError({
networkError: err,
}),
);
});
});
}
public fetchQuery<T>(
queryId: string,
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<ExecutionResult> {
const {
variables = {},
metadata = null,
fetchPolicy = 'cache-first', // cache-first is the default fetch policy.
} = options;
const { queryDoc } = this.transformQueryDocument(options);
const queryString = print(queryDoc);
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 } = diffQueryAgainstStore({
query: queryDoc,
store: this.reduxRootSelector(this.store.getState()).data,
variables,
returnPartialData: true,
fragmentMatcherFunction: this.fragmentMatcher.match,
config: this.reducerConfig,
});
// If we're in here, only fetch if we have missing fields
needToFetch = isMissing || 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.queryDocuments[queryId] = queryDoc;
this.queryStore.initQuery({
queryId,
queryString,
document: queryDoc,
storePreviousVariables: shouldFetch,
variables,
isPoll: fetchType === FetchType.poll,
isRefetch: fetchType === FetchType.refetch,
metadata,
fetchMoreForQueryId,
});
this.broadcastQueries();
if (QueryManager.EMIT_REDUX_ACTIONS) {
this.store.dispatch({
type: 'APOLLO_QUERY_INIT',
queryString,
document: queryDoc,
operationName: getOperationName(queryDoc),
variables,
fetchPolicy,
queryId,
requestId,
// we store the old variables in order to trigger "loading new variables"
// state if we know we will go to the server
storePreviousVariables: shouldFetch,
isPoll: fetchType === FetchType.poll,
isRefetch: fetchType === FetchType.refetch,
fetchMoreForQueryId,
metadata,
});
}
this.lastRequestId[queryId] = requestId;
// 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 (shouldDispatchClientResult) {
this.queryStore.markQueryResultClient(queryId, !shouldFetch);
this.broadcastQueries();
if (QueryManager.EMIT_REDUX_ACTIONS) {
this.store.dispatch({
type: 'APOLLO_QUERY_RESULT_CLIENT',
result: { data: storeResult },
variables,
document: queryDoc,
operationName: getOperationName(queryDoc),
complete: !shouldFetch,
queryId,
requestId,
});
}
}
if (shouldFetch) {
const networkResult = this.fetchRequest({
requestId,
queryId,
document: queryDoc,
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 {
if (requestId >= (this.lastRequestId[queryId] || 1)) {
if (QueryManager.EMIT_REDUX_ACTIONS) {
this.store.dispatch({
type: 'APOLLO_QUERY_ERROR',
error,
queryId,
requestId,
fetchMoreForQueryId,
});
}
this.queryStore.markQueryError(queryId, error, 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 lastResult: ApolloQueryResult<T>;
let previouslyHadError: boolean = false;
return (queryStoreValue: QueryStoreValue) => {
// The query store value can be undefined in the event of a store
// reset.
if (!queryStoreValue) {
return;
}
// 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);
const storedQuery = this.observableQueries[queryId];
const fetchPolicy = storedQuery
? storedQuery.observableQuery.options.fetchPolicy
: options.fetchPolicy;
if (fetchPolicy === 'standby') {
// don't watch the store for queries on standby
return;
}
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
) {
// XXX Currently, returning errors and data is exclusive because we
// don't handle partial results
// If we have either a GraphQL error or a network error, we create
// an error and tell the observer about it.
if (
(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 {
const { result: data, isMissing } = diffQueryAgainstStore({
store: this.getDataWithOptimisticResults(),
query: this.queryDocuments[queryId],
variables:
queryStoreValue.previousVariables || queryStoreValue.variables,
config: this.reducerConfig,
fragmentMatcherFunction: this.fragmentMatcher.match,
previousResult: lastResult && lastResult.data,
});
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 (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) {
lastResult = resultFromStore;
try {
observer.next(maybeDeepFreeze(resultFromStore));
} catch (e) {
// Throw error outside this control flow to avoid breaking Apollo's state
setTimeout(() => {
throw e;
}, 0);
}
}
}
previouslyHadError = false;
} catch (error) {
previouslyHadError = true;
if (observer.error) {
observer.error(
new ApolloError({
networkError: error,
}),
);
}
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 as any).returnPartialData) {
throw new Error(
'returnPartialData option is no longer supported since Apollo Client 1.0.',
);
}
if ((options as any).forceFetch) {
throw new Error(
'forceFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.',
);
}
if ((options as any).noFetch) {
throw new Error(
'noFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.',
);
}
if (options.fetchPolicy === 'standby') {
throw new 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;
}
let transformedOptions = { ...options } as WatchQueryOptions;
// if (this.addTypename) {
// transformedOptions.query = addTypenameToDocument(transformedOptions.query);
// }
let observableQuery = new ObservableQuery<T>({
scheduler: this.scheduler,
options: transformedOptions,
shouldSubscribe: shouldSubscribe,
});
return observableQuery;
}
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 ((options as any).forceFetch) {
throw new Error(
'forceFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.',
);
}
if ((options as any).noFetch) {
throw new Error(
'noFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.',
);
}
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.broadcastQueries();
if (QueryManager.EMIT_REDUX_ACTIONS) {
this.store.dispatch({
type: 'APOLLO_QUERY_STOP',
queryId,
});
}
}
public getApolloState(): Store {
return this.reduxRootSelector(this.store.getState());
}
public selectApolloState(store: any) {
return this.reduxRootSelector(store.getState());
}
public getInitialState(): { data: Object } {
return { data: this.getApolloState().data };
}
public getDataWithOptimisticResults(): NormalizedCache {
return getDataWithOptimisticResults(this.getApolloState());
}
public addQueryListener(queryId: string, listener: QueryListener) {
this.queryListeners[queryId] = this.queryListeners[queryId] || [];
this.queryListeners[queryId].push(listener);
}
// 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.observableQueries[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.observableQueries[queryId].observableQuery;
const definition = getQueryDefinition(observableQuery.options.query);
const queryName = definition.name ? definition.name.value : null;
delete this.observableQueries[queryId];
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.'));
});
this.queryStore.reset(Object.keys(this.observableQueries));
this.store.dispatch({
type: 'APOLLO_STORE_RESET',
observableQueryIds: Object.keys(this.observableQueries),
});
this.mutationStore.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>>[] = [];
Object.keys(this.observableQueries).forEach(queryId => {
const storeQuery = this.queryStore.get(queryId);
const fetchPolicy = this.observableQueries[queryId].observableQuery
.options.fetchPolicy;
if (fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby') {
observableQueryPromises.push(
this.observableQueries[queryId].observableQuery.refetch(),
);
}
});
return 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((error: Error) => undefined);
return queryId;
}
public startGraphQLSubscription(
options: SubscriptionOptions,
): Observable<any> {
const { query } = options;
let transformedDoc = query;
// Apply the query transformer if one has been provided.
if (this.addTypename) {
transformedDoc = addTypenameToDocument(transformedDoc);
}
const variables = assign(
{},
getDefaultValues(getOperationDefinition(query)),
options.variables,
);
const request: Request = {
query: transformedDoc,
variables,
operationName: getOperationName(transformedDoc),
};
let subId: number;
let observers: Observer<any>[] = [];
return new Observable(observer => {
observers.push(observer);
// TODO REFACTOR: the result here is not a normal GraphQL result.
// If this is the first observer, actually initiate the network subscription