-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
RelayStoreData.js
795 lines (737 loc) · 23.7 KB
/
RelayStoreData.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
/**
* 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
*/
'use strict';
const GraphQLQueryRunner = require('../legacy/store/GraphQLQueryRunner');
const GraphQLRange = require('../legacy/store/GraphQLRange');
const GraphQLStoreChangeEmitter = require('../legacy/store/GraphQLStoreChangeEmitter');
const GraphQLStoreRangeUtils = require('../legacy/store/GraphQLStoreRangeUtils');
const QueryBuilder = require('../query/QueryBuilder');
const RelayChangeTracker = require('./RelayChangeTracker');
const RelayClassicRecordState = require('./RelayClassicRecordState');
const RelayMetaRoute = require('../route/RelayMetaRoute');
const RelayMutationQueue = require('../mutation/RelayMutationQueue');
const RelayNetworkLayer = require('../network/RelayNetworkLayer');
const RelayNodeInterface = require('../interface/RelayNodeInterface');
const RelayPendingQueryTracker = require('./RelayPendingQueryTracker');
const RelayQuery = require('../query/RelayQuery');
const RelayQueryPath = require('../query/RelayQueryPath');
const RelayQueryTracker = require('./RelayQueryTracker');
const RelayQueryWriter = require('./RelayQueryWriter');
const RelayRecord = require('./RelayRecord');
const RelayRecordStore = require('./RelayRecordStore');
const RelayRecordWriter = require('./RelayRecordWriter');
const RelayTaskQueue = require('../tools/RelayTaskQueue');
const forEachObject = require('forEachObject');
const generateForceIndex = require('../legacy/store/generateForceIndex');
const invariant = require('invariant');
const mapObject = require('mapObject');
const nullthrows = require('nullthrows');
const writeRelayQueryPayload = require('../traversal/writeRelayQueryPayload');
const writeRelayUpdatePayload = require('../traversal/writeRelayUpdatePayload');
const {
restoreFragmentDataFromCache,
restoreQueriesDataFromCache,
} = require('./restoreRelayCacheData');
const {ConnectionInterface, RelayProfiler} = require('relay-runtime');
import type {QueryPath} from '../query/RelayQueryPath';
import type {
ClientMutationID,
NodeRangeMap,
QueryPayload,
RelayQuerySet,
RootCallMap,
UpdateOptions,
} from '../tools/RelayInternalTypes';
import type {TaskScheduler} from '../tools/RelayTaskQueue';
import type {
Abortable,
CacheManager,
CacheProcessorCallbacks,
} from '../tools/RelayTypes';
import type {ChangeSet} from './RelayChangeTracker';
import type {RecordMap} from './RelayRecord';
import type {DataID} from 'relay-runtime';
const {ID, ID_TYPE, NODE, NODE_TYPE, TYPENAME} = RelayNodeInterface;
const {ROOT_ID} = require('./RelayStoreConstants');
const {EXISTENT} = RelayClassicRecordState;
const idField = RelayQuery.Field.build({
fieldName: ID,
type: 'String',
});
const typeField = RelayQuery.Field.build({
fieldName: TYPENAME,
type: 'String',
});
/**
* @internal
*
* Wraps the data caches and associated metadata tracking objects used by
* GraphQLStore/RelayStore.
*/
class RelayStoreData {
_cacheManager: ?CacheManager;
_cachedRecords: RecordMap;
_cachedRootCallMap: RootCallMap;
_cachedStore: RelayRecordStore;
_changeEmitter: GraphQLStoreChangeEmitter;
_mutationQueue: RelayMutationQueue;
_networkLayer: RelayNetworkLayer;
_nodeRangeMap: NodeRangeMap;
_pendingQueryTracker: RelayPendingQueryTracker;
_records: RecordMap;
_queuedRecords: RecordMap;
_queuedStore: RelayRecordStore;
_recordStore: RelayRecordStore;
_queryTracker: ?RelayQueryTracker;
_queryRunner: GraphQLQueryRunner;
_rangeData: GraphQLStoreRangeUtils;
_rootCallMap: RootCallMap;
_taskQueue: RelayTaskQueue;
constructor(
cachedRecords?: RecordMap = {},
cachedRootCallMap?: RootCallMap = {},
queuedRecords?: RecordMap = {},
records?: RecordMap = {},
rootCallMap?: RootCallMap = {},
nodeRangeMap?: NodeRangeMap = {},
rangeData?: GraphQLStoreRangeUtils = new GraphQLStoreRangeUtils(),
) {
this._cacheManager = null;
this._cachedRecords = cachedRecords;
this._cachedRootCallMap = cachedRootCallMap;
this._cachedStore = new RelayRecordStore(
{cachedRecords, records},
{cachedRootCallMap, rootCallMap},
nodeRangeMap,
);
this._changeEmitter = new GraphQLStoreChangeEmitter(rangeData);
this._mutationQueue = new RelayMutationQueue(this);
this._networkLayer = new RelayNetworkLayer();
this._nodeRangeMap = nodeRangeMap;
this._pendingQueryTracker = new RelayPendingQueryTracker(this);
this._queryRunner = new GraphQLQueryRunner(this);
this._queryTracker = new RelayQueryTracker();
this._queuedRecords = queuedRecords;
this._queuedStore = new RelayRecordStore(
{cachedRecords, queuedRecords, records},
{cachedRootCallMap, rootCallMap},
nodeRangeMap,
);
this._records = records;
this._recordStore = new RelayRecordStore(
{records},
{rootCallMap},
nodeRangeMap,
);
this._rangeData = rangeData;
this._rootCallMap = rootCallMap;
this._taskQueue = new RelayTaskQueue();
}
/**
* @internal
*
* Sets/clears the query tracker.
*
* @warning Do not use this unless your application uses only
* `RelayGraphQLMutation` for mutations.
*/
injectQueryTracker(queryTracker: ?RelayQueryTracker): void {
this._queryTracker = queryTracker;
}
/**
* Sets/clears the scheduling function used by the internal task queue to
* schedule units of work for execution.
*/
injectTaskScheduler(scheduler: ?TaskScheduler): void {
this._taskQueue.injectScheduler(scheduler);
}
/**
* Sets/clears the cache manager that is used to cache changes written to
* the store.
*/
injectCacheManager(cacheManager: ?CacheManager): void {
this._cacheManager = cacheManager;
}
clearCacheManager(): void {
this._cacheManager = null;
}
hasCacheManager(): boolean {
return !!this._cacheManager;
}
getCacheManager(): ?CacheManager {
return this._cacheManager;
}
/**
* Returns whether a given record is affected by an optimistic update.
*/
hasOptimisticUpdate(dataID: DataID): boolean {
dataID = this.getRangeData().getCanonicalClientID(dataID);
return this.getQueuedStore().hasOptimisticUpdate(dataID);
}
/**
* Returns a list of client mutation IDs for queued mutations whose optimistic
* updates are affecting the record corresponding the given dataID. Returns
* null if the record isn't affected by any optimistic updates.
*/
getClientMutationIDs(dataID: DataID): ?Array<ClientMutationID> {
dataID = this.getRangeData().getCanonicalClientID(dataID);
return this.getQueuedStore().getClientMutationIDs(dataID);
}
/**
* Restores data for queries incrementally from cache.
* It calls onSuccess when all the data has been loaded into memory.
* It calls onFailure when some data is unabled to be satisfied from cache.
*/
restoreQueriesFromCache(
queries: RelayQuerySet,
callbacks: CacheProcessorCallbacks,
): Abortable {
const cacheManager = this._cacheManager;
invariant(
cacheManager,
'RelayStoreData: `restoreQueriesFromCache` should only be called ' +
'when cache manager is available.',
);
const changeTracker = new RelayChangeTracker();
const profile = RelayProfiler.profile('RelayStoreData.readFromDiskCache');
return restoreQueriesDataFromCache(
queries,
this._queuedStore,
this._cachedRecords,
this._cachedRootCallMap,
cacheManager,
changeTracker,
{
onSuccess: () => {
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profile.stop();
callbacks.onSuccess && callbacks.onSuccess();
},
onFailure: () => {
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profile.stop();
callbacks.onFailure && callbacks.onFailure();
},
},
);
}
/**
* Restores data for a fragment incrementally from cache.
* It calls onSuccess when all the data has been loaded into memory.
* It calls onFailure when some data is unabled to be satisfied from cache.
*/
restoreFragmentFromCache(
dataID: DataID,
fragment: RelayQuery.Fragment,
path: QueryPath,
callbacks: CacheProcessorCallbacks,
): Abortable {
const cacheManager = this._cacheManager;
invariant(
cacheManager,
'RelayStoreData: `restoreFragmentFromCache` should only be called when ' +
'cache manager is available.',
);
const changeTracker = new RelayChangeTracker();
const profile = RelayProfiler.profile(
'RelayStoreData.readFragmentFromDiskCache',
);
return restoreFragmentDataFromCache(
dataID,
fragment,
path,
this._queuedStore,
this._cachedRecords,
this._cachedRootCallMap,
cacheManager,
changeTracker,
{
onSuccess: () => {
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profile.stop();
callbacks.onSuccess && callbacks.onSuccess();
},
onFailure: () => {
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profile.stop();
callbacks.onFailure && callbacks.onFailure();
},
},
);
}
/**
* Write the results of an OSS query, which can have multiple root fields,
* updating both the root call map (for consistency with classic queries)
* and the root record (for consistency with modern queries/fragments).
*/
handleOSSQueryPayload(
query: RelayQuery.OSSQuery,
payload: QueryPayload,
forceIndex: ?number,
): void {
const profiler = RelayProfiler.profile('RelayStoreData.handleQueryPayload');
const changeTracker = new RelayChangeTracker();
const recordWriter = this.getRecordWriter();
const writer = new RelayQueryWriter(
this._queuedStore,
recordWriter,
this._queryTracker,
changeTracker,
{
forceIndex,
updateTrackedQueries: true,
},
);
getRootsWithPayloads(query, payload).forEach(
({field, root, rootPayload}) => {
// Write the results of the field-specific query
writeRelayQueryPayload(writer, root, rootPayload);
// Ensure the root record exists
const path = RelayQueryPath.getRootRecordPath();
recordWriter.putRecord(ROOT_ID, query.getType(), path);
if (this._queuedStore.getRecordState(ROOT_ID) !== EXISTENT) {
changeTracker.createID(ROOT_ID);
} else {
changeTracker.updateID(ROOT_ID);
}
// Collect linked record ids for this root field
const dataIDs = [];
RelayNodeInterface.getResultsFromPayload(root, rootPayload).forEach(
({result, rootCallInfo}) => {
const {storageKey, identifyingArgKey} = rootCallInfo;
const dataID = recordWriter.getDataID(
storageKey,
identifyingArgKey,
);
if (dataID != null) {
dataIDs.push(dataID);
}
},
);
// Write the field to the root record
const storageKey = field.getStorageKey();
if (field.isPlural()) {
recordWriter.putLinkedRecordIDs(ROOT_ID, storageKey, dataIDs);
} else {
const dataID = dataIDs[0];
if (dataID != null) {
recordWriter.putLinkedRecordID(ROOT_ID, storageKey, dataID);
} else {
recordWriter.putField(ROOT_ID, storageKey, null);
}
}
},
);
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profiler.stop();
}
/**
* Write the results of a query into the base record store.
*/
handleQueryPayload(
query: RelayQuery.Root,
payload: QueryPayload,
forceIndex: ?number,
): void {
const profiler = RelayProfiler.profile('RelayStoreData.handleQueryPayload');
const changeTracker = new RelayChangeTracker();
const writer = new RelayQueryWriter(
this._queuedStore,
this.getRecordWriter(),
this._queryTracker,
changeTracker,
{
forceIndex,
updateTrackedQueries: true,
},
);
writeRelayQueryPayload(writer, query, payload);
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profiler.stop();
}
/**
* Write the result of a fragment into the base record store.
*/
handleFragmentPayload(
dataID: DataID,
fragment: RelayQuery.Fragment,
path: QueryPath,
payload: QueryPayload,
forceIndex: ?number,
): void {
const profiler = RelayProfiler.profile(
'RelayStoreData.handleFragmentPayload',
);
const changeTracker = new RelayChangeTracker();
const writer = new RelayQueryWriter(
this._queuedStore,
this.getRecordWriter(),
this._queryTracker,
changeTracker,
{
forceIndex,
updateTrackedQueries: true,
},
);
writer.createRecordIfMissing(fragment, dataID, path, payload);
writer.writePayload(fragment, dataID, payload, path);
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profiler.stop();
}
/**
* Write the results of an update into the base record store.
*/
handleUpdatePayload(
operation: RelayQuery.Operation,
payload: {[key: string]: mixed},
{configs, isOptimisticUpdate}: UpdateOptions,
): void {
const profiler = RelayProfiler.profile(
'RelayStoreData.handleUpdatePayload',
);
const changeTracker = new RelayChangeTracker();
let recordWriter;
if (isOptimisticUpdate) {
const {CLIENT_MUTATION_ID} = ConnectionInterface.get();
const clientMutationID = payload[CLIENT_MUTATION_ID];
invariant(
typeof clientMutationID === 'string',
'RelayStoreData.handleUpdatePayload(): Expected optimistic payload ' +
'to have a valid `%s`.',
CLIENT_MUTATION_ID,
);
recordWriter = this.getRecordWriterForOptimisticMutation(
clientMutationID,
);
} else {
recordWriter = this._getRecordWriterForMutation();
}
const writer = new RelayQueryWriter(
this._queuedStore,
recordWriter,
this._queryTracker,
changeTracker,
{
forceIndex: generateForceIndex(),
isOptimisticUpdate,
updateTrackedQueries: false,
},
);
writeRelayUpdatePayload(writer, operation, payload, {
configs,
isOptimisticUpdate,
});
this._handleChangedAndNewDataIDs(changeTracker.getChangeSet());
profiler.stop();
}
/**
* Given a query fragment and a data ID, returns a root query that applies
* the fragment to the object specified by the data ID.
*/
buildFragmentQueryForDataID(
fragment: RelayQuery.Fragment,
dataID: DataID,
): RelayQuery.Root {
if (RelayRecord.isClientID(dataID)) {
const path = this._queuedStore.getPathToRecord(
this._rangeData.getCanonicalClientID(dataID),
);
invariant(
path,
'RelayStoreData.buildFragmentQueryForDataID(): Cannot refetch ' +
'record `%s` without a path.',
dataID,
);
return RelayQueryPath.getQuery(this._cachedStore, path, fragment);
}
// Fragment fields cannot be spread directly into the root because they
// may not exist on the `Node` type.
return RelayQuery.Root.build(
fragment.getDebugName() || 'UnknownQuery',
NODE,
dataID,
[idField, typeField, fragment],
{
identifyingArgName: ID,
identifyingArgType: ID_TYPE,
isAbstract: true,
isDeferred: false,
isPlural: false,
},
NODE_TYPE,
);
}
getNodeData(): RecordMap {
return this._records;
}
getQueuedData(): RecordMap {
return this._queuedRecords;
}
clearQueuedData(): void {
forEachObject(this._queuedRecords, (_, key) => {
delete this._queuedRecords[key];
this._changeEmitter.broadcastChangeForID(key);
});
}
getCachedData(): RecordMap {
return this._cachedRecords;
}
getMutationQueue(): RelayMutationQueue {
return this._mutationQueue;
}
getNetworkLayer(): RelayNetworkLayer {
return this._networkLayer;
}
/**
* Get the record store with only the cached and base data (no queued data).
*/
getCachedStore(): RelayRecordStore {
return this._cachedStore;
}
/**
* Get the record store with full data (cached, base, queued).
*/
getQueuedStore(): RelayRecordStore {
return this._queuedStore;
}
/**
* Get the record store with only the base data (no queued/cached data).
*/
getRecordStore(): RelayRecordStore {
return this._recordStore;
}
/**
* Get the record writer for the base data.
*/
getRecordWriter(): RelayRecordWriter {
return new RelayRecordWriter(
this._records,
this._rootCallMap,
false, // isOptimistic
(this._nodeRangeMap: $FlowFixMe),
this._cacheManager ? this._cacheManager.getQueryWriter() : null,
);
}
getQueryTracker(): ?RelayQueryTracker {
return this._queryTracker;
}
getQueryRunner(): GraphQLQueryRunner {
return this._queryRunner;
}
getChangeEmitter(): GraphQLStoreChangeEmitter {
return this._changeEmitter;
}
getRangeData(): GraphQLStoreRangeUtils {
return this._rangeData;
}
getPendingQueryTracker(): RelayPendingQueryTracker {
return this._pendingQueryTracker;
}
getTaskQueue(): RelayTaskQueue {
return this._taskQueue;
}
/**
* @deprecated
*
* Used temporarily by GraphQLStore, but all updates to this object are now
* handled through a `RelayRecordStore` instance.
*/
getRootCallData(): RootCallMap {
return this._rootCallMap;
}
_isStoreDataEmpty(): boolean {
return (
Object.keys(this._records).length === 0 &&
Object.keys(this._queuedRecords).length === 0 &&
Object.keys(this._cachedRecords).length === 0
);
}
/**
* Given a ChangeSet, broadcasts changes for updated DataIDs
* and registers new DataIDs with the garbage collector.
*/
_handleChangedAndNewDataIDs(changeSet: ChangeSet): void {
const updatedDataIDs = Object.keys(changeSet.updated);
const createdDataIDs = Object.keys(changeSet.created);
updatedDataIDs.forEach(id => this._changeEmitter.broadcastChangeForID(id));
// Containers may be subscribed to "new" records in the case where they
// were previously garbage collected or where the link was incrementally
// loaded from cache prior to the linked record.
createdDataIDs.forEach(id => {
this._changeEmitter.broadcastChangeForID(id);
});
}
_getRecordWriterForMutation(): RelayRecordWriter {
return new RelayRecordWriter(
this._records,
this._rootCallMap,
false, // isOptimistic
(this._nodeRangeMap: $FlowFixMe),
this._cacheManager ? this._cacheManager.getMutationWriter() : null,
);
}
getRecordWriterForOptimisticMutation(
clientMutationID: ClientMutationID,
): RelayRecordWriter {
return new RelayRecordWriter(
this._queuedRecords,
this._rootCallMap,
true, // isOptimistic
this._nodeRangeMap,
null, // don't cache optimistic data
clientMutationID,
);
}
toJSON() {
/**
* A util function which remove the querypath from the record. Used to stringify the RecordMap.
*/
const getRecordsWithoutPaths = (recordMap: ?RecordMap) => {
if (!recordMap) {
return null;
}
return mapObject(recordMap, record => {
const nextRecord = {...record};
delete nextRecord[RelayRecord.MetadataKey.PATH];
return nextRecord;
});
};
return {
cachedRecords: getRecordsWithoutPaths(this._cachedRecords),
cachedRootCallMap: this._cachedRootCallMap,
queuedRecords: getRecordsWithoutPaths(this._queuedRecords),
records: getRecordsWithoutPaths(this._records),
rootCallMap: this._rootCallMap,
nodeRangeMap: this._nodeRangeMap,
};
}
/* $FlowFixMe: This comment suppresses an error caught by Flow 0.59 which was
* not caught before. Most likely, this error is because an exported function
* parameter is missing an annotation. Without an annotation, these parameters
* are uncovered by Flow. */
static fromJSON(obj): RelayStoreData {
invariant(obj, 'RelayStoreData: JSON object is empty');
const {
cachedRecords,
cachedRootCallMap,
queuedRecords,
records,
rootCallMap,
nodeRangeMap,
} = obj;
deserializeRecordRanges(cachedRecords);
deserializeRecordRanges(queuedRecords);
deserializeRecordRanges(records);
return new RelayStoreData(
cachedRecords,
cachedRootCallMap,
queuedRecords,
records,
rootCallMap,
nodeRangeMap,
);
}
}
/**
* A helper function which checks for serialized GraphQLRange
* instances and deserializes them in toJSON()
*/
function deserializeRecordRanges(records) {
for (const key in records) {
const record = records[key];
const range = record.__range__;
if (range) {
record.__range__ = GraphQLRange.fromJSON(range);
}
}
}
/**
* Given an OSS query and response, returns an array of information
* corresponding to each root field with items as follows:
* - `field`: the root field from the input query
* - `root`: the synthesized RelayQueryRoot corresponding to that field
* - `rootPayload`: the payload for that `root`
*/
function getRootsWithPayloads(
query: RelayQuery.OSSQuery,
response: Object,
): Array<{
field: RelayQuery.Field,
root: RelayQuery.Root,
rootPayload: Object,
}> {
const results = [];
query.getChildren().forEach(child => {
const field = child;
if (!(field instanceof RelayQuery.Field) || !field.canHaveSubselections()) {
// Only care about linked fields
return;
}
// Get the concrete field from the RelayQueryField
const concreteField = nullthrows(
QueryBuilder.getField(field.getConcreteQueryNode()),
);
// Build the identifying argument for the query
let identifyingArgName;
let identifyingArgType;
const identifyingArg = concreteField.calls && concreteField.calls[0];
if (identifyingArg) {
identifyingArgName = identifyingArg.name;
identifyingArgType =
identifyingArg.metadata && identifyingArg.metadata.type;
}
// Build the concrete query
const concreteQuery = {
calls: concreteField.calls,
children: concreteField.children,
directives: [], // @include/@skip directives are processed within getChildren()
fieldName: concreteField.fieldName,
isDeferred: false,
kind: 'Query',
metadata: {
identifyingArgName,
identifyingArgType,
isAbstract: concreteField.metadata && concreteField.metadata.isAbstract,
isPlural: concreteField.metadata && concreteField.metadata.isPlural,
},
name: query.getName(),
// Note that classic queries are typed as the type of the root field, not
// the `Query` type
type: field.getType(),
};
// Construct a root query
const root = RelayQuery.Root.create(
concreteQuery,
RelayMetaRoute.get('$RelayEnvironment'),
query.getVariables(),
);
// Construct the payload that would have been returned had `root` been
// used to fetch data.
const serializationKey = field.getSerializationKey();
const rootPayload = {};
if (!response.hasOwnProperty(serializationKey)) {
// Data is missing for this field. This can occur when the field is empty
// due to a failing conditional (@include/@skip) in its subtree.
return;
}
rootPayload[root.getFieldName()] = response[serializationKey];
results.push({
field,
root,
rootPayload,
});
});
return results;
}
RelayProfiler.instrumentMethods(RelayStoreData.prototype, {
handleQueryPayload: 'RelayStoreData.prototype.handleQueryPayload',
handleUpdatePayload: 'RelayStoreData.prototype.handleUpdatePayload',
});
module.exports = RelayStoreData;