-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
RelayStoreTypes.js
1163 lines (1052 loc) · 34 KB
/
RelayStoreTypes.js
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
import type {
ActorIdentifier,
IActorEnvironment,
} from '../multi-actor-environment';
import type {
GraphQLResponse,
INetwork,
PayloadData,
PayloadError,
ReactFlightServerError,
ReactFlightServerTree,
UploadableMap,
} from '../network/RelayNetworkTypes';
import type RelayObservable from '../network/RelayObservable';
import type {RequestIdentifier} from '../util/getRequestIdentifier';
import type {
NormalizationArgument,
NormalizationLinkedField,
NormalizationRootNode,
NormalizationScalarField,
NormalizationSelectableNode,
} from '../util/NormalizationNode';
import type {ReaderFragment} from '../util/ReaderNode';
import type {
ConcreteRequest,
RequestParameters,
} from '../util/RelayConcreteNode';
import type {
CacheConfig,
DataID,
Disposable,
RenderPolicy,
Variables,
} from '../util/RelayRuntimeTypes';
import type {InvalidationState} from './RelayModernStore';
import type RelayOperationTracker from './RelayOperationTracker';
import type {RecordState} from './RelayRecordState';
export opaque type FragmentType = empty;
export type OperationTracker = RelayOperationTracker;
export type MutationParameters = {|
+response: {...},
+variables: interface {},
+rawResponse?: {...},
|};
/*
* An individual cached graph object.
*/
export type Record = {[key: string]: mixed, ...};
/**
* A collection of records keyed by id.
*/
export type RecordObjectMap = {[DataID]: ?Record};
export type FragmentMap = {[key: string]: ReaderFragment, ...};
/**
* The results of a selector given a store/RecordSource.
*/
export type SelectorData = {[key: string]: mixed, ...};
export type SingularReaderSelector = {|
+kind: 'SingularReaderSelector',
+dataID: DataID,
+isWithinUnmatchedTypeRefinement: boolean,
+node: ReaderFragment,
+owner: RequestDescriptor,
+variables: Variables,
|};
export type ReaderSelector = SingularReaderSelector | PluralReaderSelector;
export type PluralReaderSelector = {|
+kind: 'PluralReaderSelector',
+selectors: $ReadOnlyArray<SingularReaderSelector>,
|};
export type RequestDescriptor = {|
+identifier: RequestIdentifier,
+node: ConcreteRequest,
+variables: Variables,
+cacheConfig: ?CacheConfig,
|};
/**
* A selector defines the starting point for a traversal into the graph for the
* purposes of targeting a subgraph.
*/
export type NormalizationSelector = {|
+dataID: DataID,
+node: NormalizationSelectableNode,
+variables: Variables,
|};
type MissingRequiredField = {|
path: string,
owner: string,
|};
export type MissingRequiredFields =
| {|action: 'THROW', field: MissingRequiredField|}
| {|action: 'LOG', fields: Array<MissingRequiredField>|};
/**
* A representation of a selector and its results at a particular point in time.
*/
export type Snapshot = {|
+data: ?SelectorData,
+isMissingData: boolean,
+seenRecords: DataIDSet,
+selector: SingularReaderSelector,
+missingRequiredFields: ?MissingRequiredFields,
|};
/**
* An operation selector describes a specific instance of a GraphQL operation
* with variables applied.
*
* - `root`: a selector intended for processing server results or retaining
* response data in the store.
* - `fragment`: a selector intended for use in reading or subscribing to
* the results of the the operation.
*/
export type OperationDescriptor = {|
+fragment: SingularReaderSelector,
+request: RequestDescriptor,
+root: NormalizationSelector,
|};
/**
* Arbitrary data e.g. received by a container as props.
*/
export type Props = {[key: string]: mixed, ...};
/**
* The type of the `relay` property set on React context by the React/Relay
* integration layer (e.g. QueryRenderer, FragmentContainer, etc).
*/
export type RelayContext = {|
environment: IEnvironment,
getEnvironmentForActor?: ?(
actorIdentifier: ActorIdentifier,
) => IActorEnvironment,
|};
/**
* The results of reading the results of a FragmentMap given some input
* `Props`.
*/
export type FragmentSpecResults = {[key: string]: mixed, ...};
/**
* A utility for resolving and subscribing to the results of a fragment spec
* (key -> fragment mapping) given some "props" that determine the root ID
* and variables to use when reading each fragment. When props are changed via
* `setProps()`, the resolver will update its results and subscriptions
* accordingly. Internally, the resolver:
* - Converts the fragment map & props map into a map of `Selector`s.
* - Removes any resolvers for any props that became null.
* - Creates resolvers for any props that became non-null.
* - Updates resolvers with the latest props.
*/
export interface FragmentSpecResolver {
/**
* Stop watching for changes to the results of the fragments.
*/
dispose(): void;
/**
* Get the current results.
*/
resolve(): FragmentSpecResults;
/**
* Update the resolver with new inputs. Call `resolve()` to get the updated
* results.
*/
setProps(props: Props): void;
/**
* Override the variables used to read the results of the fragments. Call
* `resolve()` to get the updated results.
*/
setVariables(variables: Variables, node: ConcreteRequest): void;
/**
* Subscribe to resolver updates.
* Overrides existing callback (if one has been specified).
*/
setCallback(props: Props, callback: () => void): void;
}
/**
* A read-only interface for accessing cached graph data.
*/
export interface RecordSource {
get(dataID: DataID): ?Record;
getRecordIDs(): Array<DataID>;
getStatus(dataID: DataID): RecordState;
has(dataID: DataID): boolean;
size(): number;
toJSON(): {[DataID]: ?Record, ...};
}
/**
* A read/write interface for accessing and updating graph data.
*/
export interface MutableRecordSource extends RecordSource {
clear(): void;
delete(dataID: DataID): void;
remove(dataID: DataID): void;
set(dataID: DataID, record: Record): void;
}
export type CheckOptions = {|
handlers: $ReadOnlyArray<MissingFieldHandler>,
defaultActorIdentifier: ActorIdentifier,
getTargetForActor: (actorIdentifier: ActorIdentifier) => MutableRecordSource,
getSourceForActor: (actorIdentifier: ActorIdentifier) => RecordSource,
|};
export type OperationAvailability =
| {|status: 'available', fetchTime: ?number|}
| {|status: 'stale'|}
| {|status: 'missing'|};
export type {InvalidationState} from './RelayModernStore';
/**
* An interface for keeping multiple views of data consistent across an
* application.
*/
export interface Store {
/**
* Get a read-only view of the store's internal RecordSource.
*/
getSource(): RecordSource;
/**
* Determine if the operation can be resolved with data in the store (i.e. no
* fields are missing).
*/
check(
operation: OperationDescriptor,
options?: CheckOptions,
): OperationAvailability;
/**
* Read the results of a selector from in-memory records in the store.
*/
lookup(selector: SingularReaderSelector): Snapshot;
/**
* Notify subscribers (see `subscribe`) of any data that was published
* (`publish()`) since the last time `notify` was called.
* Optionally provide an OperationDescriptor indicating the source operation
* that was being processed to produce this run.
*
* This method should return an array of the affected fragment owners.
*/
notify(
sourceOperation?: OperationDescriptor,
invalidateStore?: boolean,
): $ReadOnlyArray<RequestDescriptor>;
/**
* Publish new information (e.g. from the network) to the store, updating its
* internal record source. Subscribers are not immediately notified - this
* occurs when `notify()` is called.
*/
publish(source: RecordSource, idsMarkedForInvalidation?: DataIDSet): void;
/**
* Ensure that all the records necessary to fulfill the given selector are
* retained in memory. The records will not be eligible for garbage collection
* until the returned reference is disposed.
*/
retain(operation: OperationDescriptor): Disposable;
/**
* Subscribe to changes to the results of a selector. The callback is called
* when `notify()` is called *and* records have been published that affect the
* selector results relative to the last `notify()`.
*/
subscribe(
snapshot: Snapshot,
callback: (snapshot: Snapshot) => void,
): Disposable;
/**
* The method should disable garbage collection until
* the returned reference is disposed.
*/
holdGC(): Disposable;
/**
* Record a backup/snapshot of the current state of the store, including
* records and derived data such as fragment subscriptions.
* This state can be restored with restore().
*/
snapshot(): void;
/**
* Reset the state of the store to the point that snapshot() was last called.
*/
restore(): void;
/**
* Will return an opaque snapshot of the current invalidation state of
* the data ids that were provided.
*/
lookupInvalidationState(dataIDs: $ReadOnlyArray<DataID>): InvalidationState;
/**
* Given the previous invalidation state for those
* ids, this function will return:
* - false, if the invalidation state for those ids is the same, meaning
* **it has not changed**
* - true, if the invalidation state for the given ids has changed
*/
checkInvalidationState(previousInvalidationState: InvalidationState): boolean;
/**
* Will subscribe the provided callback to the invalidation state of the
* given data ids. Whenever the invalidation state for any of the provided
* ids changes, the callback will be called, and provide the latest
* invalidation state.
* Disposing of the returned disposable will remove the subscription.
*/
subscribeToInvalidationState(
invalidationState: InvalidationState,
callback: () => void,
): Disposable;
/**
* Get the current write epoch
*/
getEpoch(): number;
}
export interface StoreSubscriptions {
/**
* Subscribe to changes to the results of a selector. The callback is called
* when `updateSubscriptions()` is called *and* records have been published that affect the
* selector results relative to the last update.
*/
subscribe(
snapshot: Snapshot,
callback: (snapshot: Snapshot) => void,
): Disposable;
/**
* Record a backup/snapshot of the current state of the subscriptions.
* This state can be restored with restore().
*/
snapshotSubscriptions(source: RecordSource): void;
/**
* Reset the state of the subscriptions to the point that snapshot() was last called.
*/
restoreSubscriptions(): void;
/**
* Notifies each subscription if the snapshot for the subscription selector has changed.
* Mutates the updatedOwners array with any owners (RequestDescriptors) associated
* with the subscriptions that were notified; i.e. the owners affected by the changes.
*/
updateSubscriptions(
source: RecordSource,
updatedRecordIDs: DataIDSet,
updatedOwners: Array<RequestDescriptor>,
sourceOperation?: OperationDescriptor,
): void;
}
/**
* A type that accepts a callback and schedules it to run at some future time.
* By convention, implementations should not execute the callback immediately.
*/
export type Scheduler = (() => void) => void;
/**
* An interface for imperatively getting/setting properties of a `Record`. This interface
* is designed to allow the appearance of direct Record manipulation while
* allowing different implementations that may e.g. create a changeset of
* the modifications.
*/
export interface RecordProxy {
copyFieldsFrom(source: RecordProxy): void;
getDataID(): DataID;
getLinkedRecord(name: string, args?: ?Variables): ?RecordProxy;
getLinkedRecords(name: string, args?: ?Variables): ?Array<?RecordProxy>;
getOrCreateLinkedRecord(
name: string,
typeName: string,
args?: ?Variables,
): RecordProxy;
getType(): string;
getValue(name: string, args?: ?Variables): mixed;
setLinkedRecord(
record: RecordProxy,
name: string,
args?: ?Variables,
): RecordProxy;
setLinkedRecords(
records: Array<?RecordProxy>,
name: string,
args?: ?Variables,
): RecordProxy;
setValue(value: mixed, name: string, args?: ?Variables): RecordProxy;
invalidateRecord(): void;
}
export interface ReadOnlyRecordProxy {
getDataID(): DataID;
getLinkedRecord(name: string, args?: ?Variables): ?RecordProxy;
getLinkedRecords(name: string, args?: ?Variables): ?Array<?RecordProxy>;
getType(): string;
getValue(name: string, args?: ?Variables): mixed;
}
/**
* An interface for imperatively getting/setting properties of a `RecordSource`. This interface
* is designed to allow the appearance of direct RecordSource manipulation while
* allowing different implementations that may e.g. create a changeset of
* the modifications.
*/
export interface RecordSourceProxy {
create(dataID: DataID, typeName: string): RecordProxy;
delete(dataID: DataID): void;
get(dataID: DataID): ?RecordProxy;
getRoot(): RecordProxy;
invalidateStore(): void;
}
export interface ReadOnlyRecordSourceProxy {
get(dataID: DataID): ?ReadOnlyRecordProxy;
getRoot(): ReadOnlyRecordProxy;
}
/**
* Extends the RecordSourceProxy interface with methods for accessing the root
* fields of a Selector.
*/
export interface RecordSourceSelectorProxy extends RecordSourceProxy {
getRootField(fieldName: string): ?RecordProxy;
getPluralRootField(fieldName: string): ?Array<?RecordProxy>;
invalidateStore(): void;
}
export type LogEvent =
| {|
+name: 'suspense.fragment',
+data: mixed,
+fragment: ReaderFragment,
+isRelayHooks: boolean,
+isMissingData: boolean,
+isPromiseCached: boolean,
+pendingOperations: $ReadOnlyArray<RequestDescriptor>,
|}
| {|
+name: 'suspense.query',
+fetchPolicy: string,
+isPromiseCached: boolean,
+operation: OperationDescriptor,
+queryAvailability: ?OperationAvailability,
+renderPolicy: RenderPolicy,
|}
| {|
+name: 'queryresource.fetch',
// ID of this query resource request and will be the same
// if there is an associated queryresource.retain event.
+resourceID: number,
+operation: OperationDescriptor,
// value from ProfilerContext
+profilerContext: mixed,
// FetchPolicy from Relay Hooks
+fetchPolicy: string,
// RenderPolicy from Relay Hooks
+renderPolicy: RenderPolicy,
+queryAvailability: OperationAvailability,
+shouldFetch: boolean,
|}
| {|
+name: 'queryresource.retain',
+resourceID: number,
// value from ProfilerContext
+profilerContext: mixed,
|}
| {|
+name: 'network.info',
+networkRequestId: number,
+info: mixed,
|}
| {|
+name: 'network.start',
+networkRequestId: number,
+params: RequestParameters,
+variables: Variables,
+cacheConfig: CacheConfig,
|}
| {|
+name: 'network.next',
+networkRequestId: number,
+response: GraphQLResponse,
|}
| {|
+name: 'network.error',
+networkRequestId: number,
+error: Error,
|}
| {|
+name: 'network.complete',
+networkRequestId: number,
|}
| {|
+name: 'network.unsubscribe',
+networkRequestId: number,
|}
| {|
+name: 'execute.start',
+executeId: number,
+params: RequestParameters,
+variables: Variables,
+cacheConfig: CacheConfig,
|}
| {|
+name: 'execute.next',
+executeId: number,
+response: GraphQLResponse,
+duration: number,
|}
| {|
+name: 'execute.async.module',
+executeId: number,
+operationName: string,
+duration: number,
|}
| {|
+name: 'execute.flight.payload_deserialize',
+executeId: number,
+operationName: string,
+duration: number,
|}
| {|
+name: 'execute.error',
+executeId: number,
+error: Error,
|}
| {|
+name: 'execute.complete',
+executeId: number,
|}
| {|
+name: 'store.publish',
+source: RecordSource,
+optimistic: boolean,
|}
| {|
+name: 'store.snapshot',
|}
| {|
+name: 'store.restore',
|}
| {|
+name: 'store.gc',
+references: DataIDSet,
|}
| {|
+name: 'store.notify.start',
+sourceOperation: ?OperationDescriptor,
|}
| {|
+name: 'store.notify.complete',
+sourceOperation: ?OperationDescriptor,
+updatedRecordIDs: DataIDSet,
+invalidatedRecordIDs: DataIDSet,
|}
| {|
+name: 'store.notify.subscription',
+sourceOperation: ?OperationDescriptor,
+snapshot: Snapshot,
+nextSnapshot: Snapshot,
|}
| {|
+name: 'entrypoint.root.consume',
+profilerContext: mixed,
+rootModuleID: string,
|};
export type LogFunction = LogEvent => void;
export type LogRequestInfoFunction = mixed => void;
/**
* The public API of Relay core. Represents an encapsulated environment with its
* own in-memory cache.
*/
export interface IEnvironment {
/**
* Extra information attached to the environment instance
*/
+options: mixed;
/**
* **UNSTABLE** Event based logging API thats scoped to the environment.
*/
__log: LogFunction;
/**
* Determine if the operation can be resolved with data in the store (i.e. no
* fields are missing).
*
* Note that this operation effectively "executes" the selector against the
* cache and therefore takes time proportional to the size/complexity of the
* selector.
*/
check(operation: OperationDescriptor): OperationAvailability;
/**
* Subscribe to changes to the results of a selector. The callback is called
* when data has been committed to the store that would cause the results of
* the snapshot's selector to change.
*/
subscribe(
snapshot: Snapshot,
callback: (snapshot: Snapshot) => void,
): Disposable;
/**
* Ensure that all the records necessary to fulfill the given selector are
* retained in-memory. The records will not be eligible for garbage collection
* until the returned reference is disposed.
*/
retain(operation: OperationDescriptor): Disposable;
/**
* Apply an optimistic update to the environment. The mutation can be reverted
* by calling `dispose()` on the returned value.
*/
applyUpdate(optimisticUpdate: OptimisticUpdateFunction): Disposable;
/**
* Revert updates for the `update` function.
*/
revertUpdate(update: OptimisticUpdateFunction): void;
/**
* Revert updates for the `update` function, and apply the `replacement` update.
*/
replaceUpdate(
update: OptimisticUpdateFunction,
replacement: OptimisticUpdateFunction,
): void;
/**
* Apply an optimistic mutation response and/or updater. The mutation can be
* reverted by calling `dispose()` on the returned value.
*/
applyMutation<TMutation: MutationParameters>(
optimisticConfig: OptimisticResponseConfig<TMutation>,
): Disposable;
/**
* Commit an updater to the environment. This mutation cannot be reverted and
* should therefore not be used for optimistic updates. This is mainly
* intended for updating fields from client schema extensions.
*/
commitUpdate(updater: StoreUpdater): void;
/**
* Commit a payload to the environment using the given operation selector.
*/
commitPayload(
operationDescriptor: OperationDescriptor,
payload: PayloadData,
): void;
/**
* Get the environment's internal Network.
*/
getNetwork(): INetwork;
/**
* Get the environment's internal Store.
*/
getStore(): Store;
/**
* Returns the environment specific OperationTracker.
*/
getOperationTracker(): RelayOperationTracker;
/**
* EXPERIMENTAL
* Returns the default render policy to use when rendering a query
* that uses Relay Hooks.
*/
UNSTABLE_getDefaultRenderPolicy(): RenderPolicy;
/**
* Read the results of a selector from in-memory records in the store.
*/
lookup(selector: SingularReaderSelector): Snapshot;
/**
* Send a query to the server with Observer semantics: one or more
* responses may be returned (via `next`) over time followed by either
* the request completing (`completed`) or an error (`error`).
*
* Note: Observables are lazy, so calling this method will do nothing until
* the result is subscribed to: environment.execute({...}).subscribe({...}).
*/
execute(config: {|
operation: OperationDescriptor,
|}): RelayObservable<GraphQLResponse>;
/**
* Send a subscription to the server with Observer semantics: one or more
* responses may be returned (via `next`) over time followed by either
* the request completing (`completed`) or an error (`error`).
*
* Networks/servers that support subscriptions may choose to hold the
* subscription open indefinitely such that `complete` is not called.
*
* Note: Observables are lazy, so calling this method will do nothing until
* the result is subscribed to: environment.executeSubscription({...}).subscribe({...}).
*/
executeSubscription<TMutation: MutationParameters>(config: {|
operation: OperationDescriptor,
updater?: ?SelectorStoreUpdater<$ElementType<TMutation, 'response'>>,
|}): RelayObservable<GraphQLResponse>;
/**
* Returns an Observable of GraphQLResponse resulting from executing the
* provided Mutation operation, the result of which is then normalized and
* committed to the publish queue along with an optional optimistic response
* or updater.
*
* Note: Observables are lazy, so calling this method will do nothing until
* the result is subscribed to:
* environment.executeMutation({...}).subscribe({...}).
*/
executeMutation<TMutation: MutationParameters>(
config: ExecuteMutationConfig<TMutation>,
): RelayObservable<GraphQLResponse>;
/**
* Returns an Observable of GraphQLResponse resulting from executing the
* provided Query or Subscription operation responses, the result of which is
* then normalized and committed to the publish queue.
*
* Note: Observables are lazy, so calling this method will do nothing until
* the result is subscribed to:
* environment.executeWithSource({...}).subscribe({...}).
*/
executeWithSource({|
operation: OperationDescriptor,
source: RelayObservable<GraphQLResponse>,
|}): RelayObservable<GraphQLResponse>;
/**
* Returns true if a request is currently "active", meaning it's currently
* actively receiving payloads or downloading modules, and has not received
* a final payload yet. Note that a request might still be pending (or "in flight")
* without actively receiving payload, for example a live query or an
* active GraphQL subscription
*/
isRequestActive(requestIdentifier: string): boolean;
/**
* Returns true if the environment is for use during server side rendering.
* functions like getQueryResource key off of this in order to determine
* whether we need to set up certain caches and timeout's.
*/
isServer(): boolean;
/**
* Called by Relay when it encounters a missing field that has been annotated
* with `@required(action: LOG)`.
*/
requiredFieldLogger: RequiredFieldLogger;
}
/**
* The partial shape of an object with a '...Fragment @module(name: "...")'
* selection
*/
export type ModuleImportPointer = {
+__fragmentPropName: ?string,
+__module_component: mixed,
+$fragmentRefs: mixed,
...
};
/**
* A set of DataIDs used to track which IDs a read() operation observed and which IDs
* a publish operation updated.
*/
export type DataIDSet = Set<DataID>;
/**
* A function that updates a store (via a proxy) given the results of a "handle"
* field payload.
*/
export type Handler = {
update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void,
...
};
/**
* A payload that is used to initialize or update a "handle" field with
* information from the server.
*/
export type HandleFieldPayload = {|
// The arguments that were fetched.
+args: Variables,
// The __id of the record containing the source/handle field.
+dataID: DataID,
// The (storage) key at which the original server data was written.
+fieldKey: string,
// The name of the handle.
+handle: string,
// The (storage) key at which the handle's data should be written by the
// handler.
+handleKey: string,
// The arguments applied to the handle
+handleArgs: Variables,
|};
/**
* A payload that represents data necessary to process the results of an object
* with a `@module` fragment spread, or a Flight field's:
*
* ## @module Fragment Spread
* - args: Local arguments from the parent
* - data: The GraphQL response value for the @match field.
* - dataID: The ID of the store object linked to by the @match field.
* - operationReference: A reference to a generated module containing the
* SplitOperation with which to normalize the field's `data`.
* - variables: Query variables.
* - typeName: the type that matched.
*
* The dataID, variables, and fragmentName can be used to create a Selector
* which can in turn be used to normalize and publish the data. The dataID and
* typeName can also be used to construct a root record for normalization.
*
* ## Flight fields
* In Flight, data for additional components rendered by the requested server
* component are included in the response returned by a Flight compliant server.
*
* - data: Data used by additional components rendered by the server component
* being requested.
* - dataID: For Flight fields, this should always be ROOT_ID. This is because
* the query data isn't relative to the parent record–it's root data.
* - operationReference: The query's module that will be later used by an
* operation loader.
* - variables: The query's variables.
* - typeName: For Flight fields, this should always be ROOT_TYPE. This is
* because the query data isn't relative to the parent record–it's
* root data.
*/
export type ModuleImportPayload = {|
+kind: 'ModuleImportPayload',
+args: ?$ReadOnlyArray<NormalizationArgument>,
+data: PayloadData,
+dataID: DataID,
+operationReference: mixed,
+path: $ReadOnlyArray<string>,
+typeName: string,
+variables: Variables,
+actorIdentifier: ?ActorIdentifier,
|};
/**
* A payload that represents data necessary to process the results of an object
* with experimental actor change directive.
*
* - data: The GraphQL response value for the actor change field.
* - dataID: The ID of the store object linked to by the actor change field.
* - node: NormalizationLinkedField, where the actor change directive is used
* - path: to a field in the response
* - variables: Query variables.
* - typeName: the type that matched.
*
* The dataID, variables, and fragmentName can be used to create a Selector
* which can in turn be used to normalize and publish the data. The dataID and
* typeName can also be used to construct a root record for normalization.
*/
export type ActorPayload = {|
+kind: 'ActorPayload',
+data: PayloadData,
+dataID: DataID,
+node: NormalizationLinkedField,
+path: $ReadOnlyArray<string>,
+typeName: string,
+variables: Variables,
+actorIdentifier: ActorIdentifier,
|};
/**
* Union type of possible payload followups we may handle during normalization.
*/
export type FollowupPayload = ModuleImportPayload | ActorPayload;
/**
* Data emitted after processing a Defer or Stream node during normalization
* that describes how to process the corresponding response chunk when it
* arrives.
*/
export type DeferPlaceholder = {|
+kind: 'defer',
+data: PayloadData,
+label: string,
+path: $ReadOnlyArray<string>,
+selector: NormalizationSelector,
+typeName: string,
+actorIdentifier: ?ActorIdentifier,
|};
export type StreamPlaceholder = {|
+kind: 'stream',
+label: string,
+path: $ReadOnlyArray<string>,
+parentID: DataID,
+node: NormalizationSelectableNode,
+variables: Variables,
+actorIdentifier: ?ActorIdentifier,
|};
export type IncrementalDataPlaceholder = DeferPlaceholder | StreamPlaceholder;
/**
* A user-supplied object to load a generated operation (SplitOperation or
* ConcreteRequest) AST by a module reference. The exact format of a module
* reference is left to the application, but it must be a plain JavaScript value
* (string, number, or object/array of same).
*/
export type OperationLoader = {|
/**
* Synchronously load an operation, returning either the node or null if it
* cannot be resolved synchronously.
*/
get(reference: mixed): ?NormalizationRootNode,
/**
* Asynchronously load an operation.
*/
load(reference: mixed): Promise<?NormalizationRootNode>,
|};
/**
* A function that receives a proxy over the store and may trigger side-effects
* (indirectly) by calling `set*` methods on the store or its record proxies.
*/
export type StoreUpdater = (store: RecordSourceProxy) => void;
/**
* Similar to StoreUpdater, but accepts a proxy tied to a specific selector in
* order to easily access the root fields of a query/mutation as well as a
* second argument of the response object of the mutation.
*/
export type SelectorStoreUpdater<-TMutationResponse> = (
store: RecordSourceSelectorProxy,
// Actually SelectorData, but mixed is inconvenient to access deeply in
// product code.
data: $FlowFixMe,
) => void;
/**
* A set of configs that can be used to apply an optimistic update into the
* store.
*/
export type OptimisticUpdate<TMutation: MutationParameters> =
| OptimisticUpdateFunction
| OptimisticUpdateRelayPayload<TMutation>;
export type OptimisticUpdateFunction = {|
+storeUpdater: StoreUpdater,
|};
export type OptimisticUpdateRelayPayload<TMutation: MutationParameters> = {|
+operation: OperationDescriptor,
+payload: RelayResponsePayload,
+updater: ?SelectorStoreUpdater<$ElementType<TMutation, 'response'>>,
|};