-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathObservableQuery.ts
More file actions
2120 lines (1909 loc) · 70.6 KB
/
Copy pathObservableQuery.ts
File metadata and controls
2120 lines (1909 loc) · 70.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 { equal } from "@wry/equality";
import type { DocumentNode } from "graphql";
import type {
InteropObservable,
MonoTypeOperatorFunction,
Observer,
OperatorFunction,
Subscribable,
Subscription,
} from "rxjs";
import { BehaviorSubject, filter, Observable, share, Subject, tap } from "rxjs";
import type { Cache, MissingFieldError } from "@apollo/client/cache";
import type { MissingTree } from "@apollo/client/cache";
import type { MaybeMasked, Unmasked } from "@apollo/client/masking";
import type { DeepPartial } from "@apollo/client/utilities";
import {
isNetworkRequestInFlight,
isNetworkRequestSettled,
} from "@apollo/client/utilities";
import { __DEV__ } from "@apollo/client/utilities/environment";
import {
compact,
equalByQuery,
extensionsSymbol,
filterMap,
getOperationDefinition,
getOperationName,
getQueryDefinition,
preventUnhandledRejection,
toQueryResult,
variablesUnknownSymbol,
} from "@apollo/client/utilities/internal";
import { invariant } from "@apollo/client/utilities/invariant";
import type { ApolloClient } from "./ApolloClient.js";
import { NetworkStatus } from "./networkStatus.js";
import type { QueryManager } from "./QueryManager.js";
import type {
DataState,
DefaultContext,
ErrorLike,
GetDataState,
OperationVariables,
QueryNotification,
RefetchOn,
TypedDocumentNode,
} from "./types.js";
import type {
ErrorPolicy,
NextFetchPolicyContext,
RefetchWritePolicy,
SubscribeToMoreUpdateQueryFn,
UpdateQueryMapFn,
UpdateQueryOptions,
WatchQueryFetchPolicy,
} from "./watchQueryOptions.js";
const { assign, hasOwnProperty } = Object;
interface TrackedOperation {
/**
* This NetworkStatus will be used to override the current networkStatus
*/
override?: NetworkStatus;
/**
* Will abort tracking the operation from this ObservableQuery and remove it from `activeOperations`
*/
abort: () => void;
/**
* `query` that was used by the `ObservableQuery` as the "main query" at the time the operation was started
* This is not necessarily the same query as the query the operation itself is doing.
*/
query: DocumentNode;
variables: OperationVariables;
}
const uninitialized: ObservableQuery.Result<any> = {
loading: true,
networkStatus: NetworkStatus.loading,
data: undefined,
dataState: "empty",
partial: true,
};
const empty: ObservableQuery.Result<any> = {
loading: false,
networkStatus: NetworkStatus.ready,
data: undefined,
dataState: "empty",
partial: true,
};
const enum EmitBehavior {
/**
* Emit will be calculated by the normal rules. (`undefined` will be treated the same as this)
*/
default = 0,
/**
* This result should always be emitted, even if the result is equal to the
* previous result. (e.g. the first value after a `refetch`)
*/
force = 1,
/**
* Never emit this result, it is only used to update `currentResult`.
*/
never = 2,
/**
* This is a result carrying only a "network status change"/loading state update,
* emit according to the `notifyOnNetworkStatusChange` option.
*/
networkStatusChange = 3,
}
interface Meta {
shouldEmit?: EmitBehavior;
/** can be used to override `ObservableQuery.options.fetchPolicy` for this notification */
fetchPolicy?: WatchQueryFetchPolicy;
}
export declare namespace ObservableQuery {
export type Options<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> = {
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */
fetchPolicy: WatchQueryFetchPolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#nextFetchPolicy:member} */
nextFetchPolicy?:
| WatchQueryFetchPolicy
| ((
this: ApolloClient.WatchQueryOptions<TData, TVariables>,
currentFetchPolicy: WatchQueryFetchPolicy,
context: NextFetchPolicyContext<TData, TVariables>
) => WatchQueryFetchPolicy);
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#initialFetchPolicy:member} */
initialFetchPolicy: WatchQueryFetchPolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */
refetchWritePolicy?: RefetchWritePolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */
errorPolicy?: ErrorPolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */
context?: DefaultContext;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#pollInterval:member} */
pollInterval?: number;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#notifyOnNetworkStatusChange:member} */
notifyOnNetworkStatusChange?: boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */
returnPartialData?: boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skipPollAttempt:member} */
skipPollAttempt?: () => boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member} */
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */
variables: TVariables;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchOn:member} */
refetchOn?: RefetchOn.Option;
};
export type FetchMoreOptions<
TData,
TVariables extends OperationVariables,
TFetchData = TData,
TFetchVars extends OperationVariables = TVariables,
> = {
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member} */
query?: DocumentNode | TypedDocumentNode<TFetchData, TFetchVars>;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */
variables?: Partial<NoInfer<TFetchVars>>;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */
errorPolicy?: ErrorPolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */
context?: DefaultContext;
updateQuery?: (
previousQueryResult: Unmasked<TData>,
options: {
fetchMoreResult: Unmasked<TFetchData>;
variables: TFetchVars;
}
) => Unmasked<TData>;
};
export interface SubscribeToMoreOptions<
// eslint-disable-next-line local-rules/tdata-tvariables-order
TData = unknown,
TSubscriptionVariables extends OperationVariables = OperationVariables,
TSubscriptionData = TData,
TVariables extends OperationVariables = TSubscriptionVariables,
> {
document:
| DocumentNode
| TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;
variables?: TSubscriptionVariables;
updateQuery?: SubscribeToMoreUpdateQueryFn<
TData,
TVariables,
TSubscriptionData
>;
onError?: (error: ErrorLike) => void;
context?: DefaultContext;
}
/**
* @internal
* This describes the `WatchOptions` used by `ObservableQuery` to
* subscribe to the cache.
*/
interface CacheWatchOptions<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> extends Cache.WatchOptions<TData, TVariables> {
/**
* @internal
* We cannot suppress the broadcast completely, since that would
* result in external updates to be lost if we go from
* (external A) -> (own B) -> (external C) when A and C have the same
* value.
* Without the `own B` being broadcast, the `cache.watch` would swallow
* C.
* So instead we track the last "own diff" and suppress further processing
* in the callback.
*/
lastOwnDiff?: Cache.DiffResult<TData>;
}
export type Result<
TData,
TStates extends
DataState<TData>["dataState"] = DataState<TData>["dataState"],
> = {
/** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */
error?: ErrorLike;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#loading:member} */
loading: boolean;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */
networkStatus: NetworkStatus;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#partial:member} */
partial: boolean;
} & GetDataState<TData, TStates>;
/**
* Promise returned by `reobserve` and `refetch` methods.
*
* By default, if the `ObservableQuery` is not interested in the result
* of this operation anymore, the network operation will be cancelled.
*
* This has an additional `retain` method that can be used to keep the
* network operation running until it is finished nonetheless.
*/
interface ResultPromise<T> extends Promise<T> {
/**
* Keep the network operation running until it is finished, even if
* `ObservableQuery` unsubscribed from the operation.
*/
retain(): this;
}
export namespace DocumentationTypes {
type OperatorFunctionChain<From, To> = [];
interface ObservableMethods<TData, OperatorResult> {
/** {@inheritDoc @apollo/client!ObservableQuery#pipe:member} */
pipe(
...operators: OperatorFunctionChain<
ObservableQuery.Result<TData>,
OperatorResult
>
): Observable<OperatorResult>;
/** {@inheritDoc @apollo/client!ObservableQuery#subscribe:member} */
subscribe(
observerOrNext:
| Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>>
| ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)
): Subscription;
}
}
}
interface SubjectValue<TData, TVariables extends OperationVariables> {
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
variables: TVariables;
result: ObservableQuery.Result<TData>;
meta: Meta;
}
export class ObservableQuery<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>
implements
Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>,
InteropObservable<ObservableQuery.Result<MaybeMasked<TData>>>
{
public readonly options: ObservableQuery.Options<TData, TVariables>;
public readonly queryName?: string;
private variablesUnknown: boolean = false;
/** @internal will be read and written from `QueryInfo` */
public _lastWrite?: unknown;
// The `query` computed property will always reflect the document transformed
// by the last run query. `this.options.query` will always reflect the raw
// untransformed query to ensure document transforms with runtime conditionals
// are run on the original document.
public get query(): TypedDocumentNode<TData, TVariables> {
return this.lastQuery;
}
/**
* An object containing the variables that were provided for the query.
*/
public get variables(): TVariables {
return this.options.variables;
}
private unsubscribeFromCache?: {
(): void;
query: TypedDocumentNode<TData, TVariables>;
variables: TVariables;
};
private input!: Subject<
QueryNotification.Value<TData> & {
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
variables: TVariables;
meta: Meta;
}
>;
private subject!: BehaviorSubject<
SubjectValue<MaybeMasked<TData>, TVariables>
>;
private isTornDown: boolean;
private queryManager: QueryManager;
private subscriptions = new Set<Subscription>();
/**
* If an `ObservableQuery` is created with a `network-only` fetch policy,
* it should actually start receiving cache updates, but not before it has
* received the first result from the network.
*/
private waitForNetworkResult: boolean;
private lastQuery: DocumentNode;
private linkSubscription?: Subscription;
private pollingInfo?: {
interval: number;
timeout: ReturnType<typeof setTimeout>;
};
private get networkStatus(): NetworkStatus {
return this.subject.getValue().result.networkStatus;
}
private get cache() {
return this.queryManager.cache;
}
constructor({
queryManager,
options,
transformedQuery = queryManager.transform(options.query),
}: {
queryManager: QueryManager;
options: ApolloClient.WatchQueryOptions<TData, TVariables>;
transformedQuery?: DocumentNode | TypedDocumentNode<TData, TVariables>;
queryId?: string;
}) {
this.queryManager = queryManager;
// active state
this.waitForNetworkResult = options.fetchPolicy === "network-only";
this.isTornDown = false;
this.subscribeToMore = this.subscribeToMore.bind(this);
this.maskResult = this.maskResult.bind(this);
const {
watchQuery: { fetchPolicy: defaultFetchPolicy = "cache-first" } = {},
} = queryManager.defaultOptions;
const {
fetchPolicy = defaultFetchPolicy,
// Make sure we don't store "standby" as the initialFetchPolicy.
initialFetchPolicy = fetchPolicy === "standby" ? defaultFetchPolicy : (
fetchPolicy
),
} = options;
if (options[variablesUnknownSymbol]) {
invariant(
fetchPolicy === "standby",
"The `variablesUnknown` option can only be used together with a `standby` fetch policy."
);
this.variablesUnknown = true;
}
this.lastQuery = transformedQuery;
this.options = {
...options,
// Remember the initial options.fetchPolicy so we can revert back to this
// policy when variables change. This information can also be specified
// (or overridden) by providing options.initialFetchPolicy explicitly.
initialFetchPolicy,
// This ensures this.options.fetchPolicy always has a string value, in
// case options.fetchPolicy was not provided.
fetchPolicy,
variables: this.getVariablesWithDefaults(options.variables),
};
this.initializeObservablesQueue();
this["@@observable"] = () => this;
if (Symbol.observable) {
this[Symbol.observable] = () => this;
}
const opDef = getOperationDefinition(this.query);
this.queryName = opDef && opDef.name && opDef.name.value;
}
private initializeObservablesQueue() {
this.subject = new BehaviorSubject<
SubjectValue<MaybeMasked<TData>, TVariables>
>({
query: this.query,
variables: this.variables,
result: uninitialized,
meta: {},
});
const observable = this.subject.pipe(
tap({
subscribe: () => {
if (!this.subject.observed) {
this.reobserve();
// TODO: See if we can rework updatePolling to better handle this.
// reobserve calls updatePolling but this `subscribe` callback is
// called before the subject is subscribed to so `updatePolling`
// can't accurately detect if there is an active subscription.
// Calling it again here ensures that it can detect if it can poll
setTimeout(() => this.updatePolling());
}
},
unsubscribe: () => {
if (!this.subject.observed) {
this.tearDownQuery();
}
},
}),
filterMap(
(
{ query, variables, result: current, meta },
context: {
previous?: ObservableQuery.Result<TData>;
previousVariables?: TVariables;
}
) => {
const { shouldEmit } = meta;
if (current === uninitialized) {
// reset internal state after `ObservableQuery.reset()`
context.previous = undefined;
context.previousVariables = undefined;
}
if (
this.options.fetchPolicy === "standby" ||
shouldEmit === EmitBehavior.never
)
return;
if (shouldEmit === EmitBehavior.force) return emit();
const { previous, previousVariables } = context;
if (previous) {
const documentInfo = this.queryManager.getDocumentInfo(query);
const dataMasking = this.queryManager.dataMasking;
const maskedQuery =
dataMasking ? documentInfo.nonReactiveQuery : query;
const resultIsEqual =
dataMasking || documentInfo.hasNonreactiveDirective ?
equalByQuery(maskedQuery, previous, current, variables)
: equal(previous, current);
if (resultIsEqual && equal(previousVariables, variables)) {
return;
}
}
if (
shouldEmit === EmitBehavior.networkStatusChange &&
(!this.options.notifyOnNetworkStatusChange ||
equal(previous, current))
) {
return;
}
return emit();
function emit() {
context.previous = current;
context.previousVariables = variables;
return current;
}
},
() => ({})
)
);
this.pipe = observable.pipe.bind(observable);
this.subscribe = observable.subscribe.bind(observable);
this.input = new Subject();
// we want to feed many streams into `this.subject`, but none of them should
// be able to close `this.input`
this.input.complete = () => {};
this.input.pipe(this.operator).subscribe(this.subject);
}
// We can't use Observable['subscribe'] here as the type as it conflicts with
// the ability to infer T from Subscribable<T>. This limits the surface area
// to the non-deprecated signature which works properly with type inference.
/**
* Subscribes to the `ObservableQuery`.
* @param observerOrNext - Either an RxJS `Observer` with some or all callback methods,
* or the `next` handler that is called for each value emitted from the subscribed Observable.
* @returns A subscription reference to the registered handlers.
*/
public subscribe!: (
observerOrNext:
| Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>>
| ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)
) => Subscription;
/**
* Used to stitch together functional operators into a chain.
*
* @example
*
* ```ts
* import { filter, map } from 'rxjs';
*
* observableQuery
* .pipe(
* filter(...),
* map(...),
* )
* .subscribe(x => console.log(x));
* ```
*
* @returns The Observable result of all the operators having been called
* in the order they were passed in.
*/
public pipe!: Observable<ObservableQuery.Result<MaybeMasked<TData>>>["pipe"];
public [Symbol.observable]!: () => Subscribable<
ObservableQuery.Result<MaybeMasked<TData>>
>;
public ["@@observable"]: () => Subscribable<
ObservableQuery.Result<MaybeMasked<TData>>
>;
/**
* @internal
*/
public getCacheDiff({ optimistic = true } = {}) {
return this.cache.diff<TData>({
query: this.query,
variables: this.variables,
returnPartialData: true,
optimistic,
});
}
private getInitialResult(
initialFetchPolicy?: WatchQueryFetchPolicy
): ObservableQuery.Result<MaybeMasked<TData>> {
let fetchPolicy = initialFetchPolicy || this.options.fetchPolicy;
if (
this.queryManager.prioritizeCacheValues &&
(fetchPolicy === "network-only" || fetchPolicy === "cache-and-network")
) {
fetchPolicy = "cache-first";
}
const cacheResult = (): ObservableQuery.Result<TData> => {
const diff = this.getCacheDiff();
// TODO: queryInfo.getDiff should handle this since cache.diff returns a
// null when returnPartialData is false
const data =
this.options.returnPartialData || diff.complete ?
(diff.result as TData) ?? undefined
: undefined;
return this.maskResult({
data,
dataState:
diff.complete ? "complete"
: data === undefined ? "empty"
: "partial",
loading: !diff.complete,
networkStatus:
diff.complete ? NetworkStatus.ready : NetworkStatus.loading,
partial: !diff.complete,
} as ObservableQuery.Result<TData>);
};
switch (fetchPolicy) {
case "cache-only": {
return {
...cacheResult(),
loading: false,
networkStatus: NetworkStatus.ready,
};
}
case "cache-first":
return cacheResult();
case "cache-and-network":
return {
...cacheResult(),
loading: true,
networkStatus: NetworkStatus.loading,
};
case "standby":
return empty;
default:
return uninitialized;
}
}
private resubscribeCache() {
const { variables, fetchPolicy } = this.options;
const query = this.query;
const shouldUnsubscribe =
fetchPolicy === "standby" ||
fetchPolicy === "no-cache" ||
this.waitForNetworkResult;
const shouldResubscribe =
!isEqualQuery({ query, variables }, this.unsubscribeFromCache) &&
!this.waitForNetworkResult;
if (shouldUnsubscribe || shouldResubscribe) {
this.unsubscribeFromCache?.();
}
if (shouldUnsubscribe || !shouldResubscribe) {
return;
}
const watch: ObservableQuery.CacheWatchOptions<TData, TVariables> = {
query,
variables,
optimistic: true,
watcher: this,
callback: (diff) => {
const info = this.queryManager.getDocumentInfo(query);
if (info.hasClientExports || info.hasForcedResolvers) {
// If this is not set to something different than `diff`, we will
// not be notified about future cache changes with an equal `diff`.
// That would be the case if we are working with client-only fields
// that are forced or with `exports` fields that might change, causing
// local resolvers to return a new result.
// This is based on an implementation detail of `InMemoryCache`, which
// is not optimal - but the only alternative to this would be to
// resubscribe to the cache asynchonouly, which would bear the risk of
// missing further synchronous updates.
watch.lastDiff = undefined;
}
if (watch.lastOwnDiff === diff) {
// skip cache updates that were caused by our own writes
return;
}
const { result: previousResult } = this.subject.getValue();
if (
!diff.complete &&
// If we are trying to deliver an incomplete cache result, we avoid
// reporting it if the query has errored, otherwise we let the broadcast try
// and repair the partial result by refetching the query. This check avoids
// a situation where a query that errors and another succeeds with
// overlapping data does not report the partial data result to the errored
// query.
//
// See https://github.com/apollographql/apollo-client/issues/11400 for more
// information on this issue.
(previousResult.error ||
// Prevent to schedule a notify directly after the `ObservableQuery`
// has been `reset` (which will set the `previousResult` to `uninitialized` or `empty`)
// as in those cases, `resetCache` will manually call `refetch` with more intentional timing.
previousResult === uninitialized ||
previousResult === empty)
) {
return;
}
if (!equal(previousResult.data, diff.result)) {
this.scheduleNotify();
}
},
};
const cancelWatch = this.cache.watch(watch);
this.unsubscribeFromCache = Object.assign(
() => {
this.unsubscribeFromCache = undefined;
cancelWatch();
},
{ query, variables }
);
}
private stableLastResult?: ObservableQuery.Result<MaybeMasked<TData>>;
public getCurrentResult(): ObservableQuery.Result<MaybeMasked<TData>> {
const { result: current } = this.subject.getValue();
let value =
(
// if the `current` result is in an error state, we will always return that
// error state, even if we have no observers
current.networkStatus === NetworkStatus.error ||
// if we have observers, we are watching the cache and
// this.subject.getValue() will always be up to date
this.hasObservers() ||
// if we are using a `no-cache` fetch policy in which case this
// `ObservableQuery` cannot have been updated from the outside - in
// that case, we prefer to keep the current value
this.options.fetchPolicy === "no-cache"
) ?
current
// otherwise, the `current` value might be outdated due to missed
// external updates - calculate it again
: this.getInitialResult();
if (value === uninitialized) {
value = this.getInitialResult();
}
if (!equal(this.stableLastResult, value)) {
this.stableLastResult = value;
}
return this.stableLastResult!;
}
/**
* Update the variables of this observable query, and fetch the new results.
* This method should be preferred over `setVariables` in most use cases.
*
* Returns a `ResultPromise` with an additional `.retain()` method. Calling
* `.retain()` keeps the network operation running even if the `ObservableQuery`
* no longer requires the result.
*
* Note: `refetch()` guarantees that a value will be emitted from the
* observable, even if the result is deep equal to the previous value.
*
* @param variables - The new set of variables. If there are missing variables,
* the previous values of those variables will be used.
*/
public refetch(
variables?: Partial<TVariables>
): ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>> {
const { fetchPolicy } = this.options;
const reobserveOptions: Partial<
ObservableQuery.Options<TData, TVariables>
> = {
// Always disable polling for refetches.
pollInterval: 0,
};
// Unless the provided fetchPolicy always consults the network
// (no-cache, network-only, or cache-and-network), override it with
// network-only to force the refetch for this fetchQuery call.
if (fetchPolicy === "no-cache") {
reobserveOptions.fetchPolicy = "no-cache";
} else {
reobserveOptions.fetchPolicy = "network-only";
}
if (__DEV__ && variables && hasOwnProperty.call(variables, "variables")) {
const queryDef = getQueryDefinition(this.query);
const vars = queryDef.variableDefinitions;
if (!vars || !vars.some((v) => v.variable.name.value === "variables")) {
invariant.warn(
`Called refetch(%o) for query %o, which does not declare a $variables variable.
Did you mean to call refetch(variables) instead of refetch({ variables })?`,
variables,
queryDef.name?.value || queryDef
);
}
}
if (variables && !equal(this.variables, variables)) {
// Update the existing options with new variables
reobserveOptions.variables = this.options.variables =
this.getVariablesWithDefaults({ ...this.variables, ...variables });
}
this._lastWrite = undefined;
return this._reobserve(reobserveOptions, {
newNetworkStatus: NetworkStatus.refetch,
});
}
/**
* A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
*/
public fetchMore<
TFetchData = TData,
TFetchVars extends OperationVariables = TVariables,
>(
options: ObservableQuery.FetchMoreOptions<
TData,
TVariables,
TFetchData,
TFetchVars
>
): Promise<ApolloClient.QueryResult<TFetchData>>;
public fetchMore<
TFetchData = TData,
TFetchVars extends OperationVariables = TVariables,
>({
query,
variables,
context,
errorPolicy,
updateQuery,
}: ObservableQuery.FetchMoreOptions<
TData,
TVariables,
TFetchData,
TFetchVars
>): Promise<ApolloClient.QueryResult<TFetchData>> {
invariant(
this.options.fetchPolicy !== "cache-only",
"Cannot execute `fetchMore` for 'cache-only' query '%s'. Please use a different fetch policy.",
getOperationName(this.query, "(anonymous)")
);
const combinedOptions = {
...compact(
this.options,
{ errorPolicy: "none" },
{
query,
context,
errorPolicy,
}
),
variables: (query ? variables : (
{
...this.variables,
...variables,
}
)) as TFetchVars,
// The fetchMore request goes immediately to the network and does
// not automatically write its result to the cache (hence no-cache
// instead of network-only), because we allow the caller of
// fetchMore to provide an updateQuery callback that determines how
// the data gets written to the cache.
fetchPolicy: "no-cache",
notifyOnNetworkStatusChange: this.options.notifyOnNetworkStatusChange,
} as ApolloClient.QueryOptions<TFetchData, TFetchVars>;
combinedOptions.query = this.transformDocument(combinedOptions.query);
// If a temporary query is passed to `fetchMore`, we don't want to store
// it as the last query result since it may be an optimized query for
// pagination. We will however run the transforms on the original document
// as well as the document passed in `fetchMoreOptions` to ensure the cache
// uses the most up-to-date document which may rely on runtime conditionals.
this.lastQuery =
query ?
this.transformDocument(this.options.query)
: combinedOptions.query;
let wasUpdated = false;
const isCached = this.options.fetchPolicy !== "no-cache";
if (!isCached) {
invariant(
updateQuery,
"You must provide an `updateQuery` function when using `fetchMore` with a `no-cache` fetch policy."
);
}
const { finalize, pushNotification } = this.pushOperation(
NetworkStatus.fetchMore
);
pushNotification(
{
source: "newNetworkStatus",
kind: "N",
value: {},
},
{ shouldEmit: EmitBehavior.networkStatusChange }
);
const { promise, operator } = getTrackingOperatorPromise<TFetchData>();
const { observable } = this.queryManager.fetchObservableWithInfo(
combinedOptions,
{ networkStatus: NetworkStatus.fetchMore, exposeExtensions: true }
);
const subscription = observable
.pipe(
operator,
filter(
(
notification
): notification is Extract<
QueryNotification.FromNetwork<TFetchData>,
{ kind: "N" }
> => notification.kind === "N" && notification.source === "network"
)
)
.subscribe({
next: (notification) => {
wasUpdated = false;
const fetchMoreResult: QueryManager.Result<TFetchData> =
notification.value;
const extensions = fetchMoreResult[extensionsSymbol];
if (isNetworkRequestSettled(notification.value.networkStatus)) {
finalize();
}
if (isCached) {
// Separately getting a diff here before the batch - `onWatchUpdated` might be
// called with an `undefined` `lastDiff` on the watcher if the cache was just subscribed to.
const lastDiff = this.getCacheDiff();
// Performing this cache update inside a cache.batch transaction ensures
// any affected cache.watch watchers are notified at most once about any
// updates. Most watchers will be using the QueryInfo class, which
// responds to notifications by calling reobserveCacheFirst to deliver
// fetchMore cache results back to this ObservableQuery.
this.cache.batch({
update: (cache) => {
if (updateQuery) {
cache.updateQuery(
{
query: this.query,
variables: this.variables,
returnPartialData: true,
optimistic: false,
extensions,
},
(previous) =>
updateQuery(previous! as any, {
fetchMoreResult: fetchMoreResult.data as any,
variables: combinedOptions.variables as TFetchVars,
})
);
} else {
// If we're using a field policy instead of updateQuery, the only
// thing we need to do is write the new data to the cache using
// combinedOptions.variables (instead of this.variables, which is
// what this.updateQuery uses, because it works by abusing the
// original field value, keyed by the original variables).
cache.writeQuery({
query: combinedOptions.query,
variables: combinedOptions.variables,
data: fetchMoreResult.data as Unmasked<any>,
extensions,
});
}
},
onWatchUpdated: (watch, diff) => {
if (
watch.watcher === this &&
!equal(diff.result, lastDiff.result)
) {
wasUpdated = true;
const lastResult = this.getCurrentResult();
// Let the cache watch from resubscribeCache handle the final
// result
if (isNetworkRequestInFlight(fetchMoreResult.networkStatus)) {
pushNotification({
kind: "N",
source: "network",
value: {