-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathRelayMockPayloadGenerator.js
More file actions
1078 lines (1002 loc) · 31 KB
/
Copy pathRelayMockPayloadGenerator.js
File metadata and controls
1078 lines (1002 loc) · 31 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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall relay
*/
'use strict';
import type {
GraphQLSingularResponse,
NormalizationArgument,
NormalizationField,
NormalizationLinkedField,
NormalizationOperation,
NormalizationScalarField,
NormalizationSelection,
NormalizationSplitOperation,
OperationDescriptor,
Variables,
} from 'relay-runtime';
import type {GraphQLResponseWithData} from 'relay-runtime/network/RelayNetworkTypes';
import type {GraphQLResponse} from 'relay-runtime/network/RelayNetworkTypes';
const invariant = require('invariant');
const {
__internal,
RelayConcreteNode,
TYPENAME_KEY,
getModuleComponentKey,
getModuleOperationKey,
} = require('relay-runtime');
const {
ACTOR_CHANGE,
CLIENT_COMPONENT,
CLIENT_EDGE_TO_CLIENT_OBJECT,
CLIENT_EDGE_TO_SERVER_OBJECT,
CLIENT_EXTENSION,
CONDITION,
CONNECTION,
DEFER,
FRAGMENT_SPREAD,
INLINE_FRAGMENT,
LINKED_FIELD,
LINKED_HANDLE,
MODULE_IMPORT,
RELAY_RESOLVER,
RELAY_LIVE_RESOLVER,
SCALAR_FIELD,
SCALAR_HANDLE,
STREAM,
TYPE_DISCRIMINATOR,
} = RelayConcreteNode;
type ValueResolver = (
typeName: ?string,
context: MockResolverContext,
plural: ?boolean,
defaultValue?: unknown,
) => unknown;
type Traversable = {
readonly selections: ReadonlyArray<NormalizationSelection>,
readonly typeName: ?string,
readonly isAbstractType: ?boolean,
readonly name: ?string,
readonly alias: ?string,
readonly args: ?{[string]: unknown, ...},
};
type MockData = {[string]: unknown, ...};
export type MockResolverContext = {
readonly parentType: ?string,
readonly name: ?string,
readonly alias: ?string,
readonly path: ?ReadonlyArray<string>,
readonly args: ?{[string]: unknown, ...},
};
type MockResolver = (
context: MockResolverContext,
generateId: () => number,
) => unknown;
export type MockResolvers = {readonly [typeName: string]: MockResolver, ...};
type SelectionMetadata = {
[selectionPath: string]: {
readonly type: string,
readonly plural: boolean,
readonly nullable: boolean,
readonly enumValues: ReadonlyArray<string> | null,
},
...
};
function createIdGenerator() {
let id = 0;
return () => {
return ++id;
};
}
const DEFAULT_MOCK_RESOLVERS: MockResolvers = {
ID(context: MockResolverContext, generateId: () => number) {
return `<${
context.parentType != null && context.parentType !== DEFAULT_MOCK_TYPENAME
? context.parentType + '-'
: ''
}mock-id-${generateId()}>`;
},
Boolean() {
return false;
},
Int() {
return 42;
},
Float() {
return 4.2;
},
};
const DEFAULT_MOCK_TYPENAME = '__MockObject';
/**
* Basic value resolver
*/
function valueResolver(
generateId: () => number,
mockResolvers: ?MockResolvers,
typeName: ?string,
context: MockResolverContext,
plural: ?boolean = false,
defaultValue?: unknown,
): unknown {
const generateValue = (possibleDefaultValue: unknown) => {
let mockValue;
const mockResolver =
typeName != null && mockResolvers != null
? mockResolvers[typeName]
: null;
if (mockResolver != null) {
mockValue = mockResolver(context, generateId);
}
if (mockValue === undefined) {
mockValue =
possibleDefaultValue ??
(typeName === 'ID'
? DEFAULT_MOCK_RESOLVERS.ID(context, generateId)
: `<mock-value-for-field-"${
context.alias ?? context.name ?? 'undefined'
}">`);
}
return mockValue;
};
return plural === true
? generateMockList(
Array.isArray(defaultValue) ? defaultValue : Array(1).fill(),
generateValue,
)
: generateValue(defaultValue);
}
function createValueResolver(mockResolvers: ?MockResolvers): ValueResolver {
const generateId = createIdGenerator();
return (...args) => {
return valueResolver(generateId, mockResolvers, ...args);
};
}
function generateMockList<T>(
placeholderArray: ReadonlyArray<unknown>,
generateListItem: (defaultValue: unknown, index?: number) => T,
): ReadonlyArray<T> {
return placeholderArray.map((possibleDefaultValue, index) =>
generateListItem(possibleDefaultValue, index),
);
}
class RelayMockPayloadGenerator {
_variables: Variables;
_resolveValue: ValueResolver;
_mockResolvers: MockResolvers;
_selectionMetadata: SelectionMetadata;
_mockClientData: boolean;
_generateDeferredPayload: boolean;
_deferredPayloads: Array<GraphQLResponseWithData>;
constructor(options: {
readonly variables: Variables,
readonly mockResolvers: MockResolvers | null,
readonly selectionMetadata: SelectionMetadata | null,
readonly mockClientData: ?boolean,
readonly generateDeferredPayload: ?boolean,
}) {
this._variables = options.variables;
this._mockResolvers = {
...DEFAULT_MOCK_RESOLVERS,
...(options.mockResolvers ?? {}),
};
this._selectionMetadata = options.selectionMetadata ?? {};
this._resolveValue = createValueResolver(this._mockResolvers);
this._mockClientData = options.mockClientData ?? false;
this._generateDeferredPayload = options.generateDeferredPayload ?? false;
this._deferredPayloads = [];
}
generate(
selections: ReadonlyArray<NormalizationSelection>,
operationType: string,
): Array<GraphQLSingularResponse> {
const defaultValues = this._getDefaultValuesForObject(
operationType,
null,
null,
[], // path
{},
);
const data = this._traverse(
{
selections,
typeName: operationType,
isAbstractType: false,
name: null,
alias: null,
args: null,
},
[], // path
null, // prevData
defaultValues,
);
return [{data}, ...this._deferredPayloads];
}
_traverse(
traversable: Traversable,
path: ReadonlyArray<string>,
prevData: ?MockData,
defaultValues: ?MockData,
): MockData {
const {selections, typeName, isAbstractType} = traversable;
return this._traverseSelections(
selections,
typeName,
isAbstractType,
path,
prevData,
defaultValues,
);
}
/**
* Generate mock values for selection of fields
*/
_traverseSelections(
selections: ReadonlyArray<NormalizationSelection>,
typeName: ?string,
isAbstractType: ?boolean,
path: ReadonlyArray<string>,
prevData: ?MockData,
defaultValues: ?MockData,
): MockData {
let mockData: ?($FlowFixMe | MockData) = prevData ?? {};
selections.forEach(selection => {
switch (selection.kind) {
case SCALAR_FIELD: {
mockData = this._mockScalar(
selection,
typeName,
path,
mockData,
defaultValues,
);
break;
}
// $FlowFixMe[incompatible-type]
/* $FlowFixMe[invalid-compare] Error discovered during Constant
* Condition roll out. See https://fburl.com/workplace/4oq3zi07. */
case CONNECTION: {
mockData = this._traverseSelections(
[selection.edges, selection.pageInfo],
typeName,
isAbstractType,
path,
prevData,
defaultValues,
);
break;
}
case LINKED_FIELD: {
mockData = this._mockLink(selection, path, mockData, defaultValues);
break;
}
case CONDITION:
const conditionValue = this._getVariableValue(selection.condition);
if (conditionValue === selection.passingValue) {
mockData = this._traverseSelections(
selection.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
}
break;
case CLIENT_EXTENSION:
if (!this._mockClientData) {
break;
}
mockData = this._traverseSelections(
selection.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
break;
case DEFER:
case STREAM: {
const isDeferreable =
selection.if == null || this._variables[selection.if];
if (this._generateDeferredPayload && isDeferreable) {
const deferredData = this._traverseSelections(
selection.selections,
typeName,
isAbstractType,
path,
{},
defaultValues,
);
this._deferredPayloads.push({
path: [...path],
label: selection.label,
data: deferredData,
});
break;
}
mockData = this._traverseSelections(
selection.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
break;
}
case CLIENT_COMPONENT: {
mockData = this._traverseSelections(
selection.fragment.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
break;
}
case FRAGMENT_SPREAD: {
const prevVariables = this._variables;
this._variables = __internal.getLocalVariables(
this._variables,
selection.fragment.argumentDefinitions,
selection.args,
);
mockData = this._traverseSelections(
selection.fragment.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
this._variables = prevVariables;
break;
}
case INLINE_FRAGMENT: {
const {abstractKey} = selection;
if (abstractKey != null) {
// Allow mocking of this inline fragment to be skipped by including
// a field like "__isNamed: false" in the mock data (e.g. to write
// tests for queries that use @alias).
const shouldMockFragment =
defaultValues?.[abstractKey] === undefined ||
!!defaultValues?.[abstractKey];
if (!shouldMockFragment) {
break;
}
if (mockData != null) {
mockData[abstractKey] = true;
}
mockData = this._traverseSelections(
selection.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
break;
}
// If it's the first time we're trying to handle fragment spread
// on this selection, we will generate data for this type.
// Next fragment spread on this selection will be added only if the
// types are matching
if (
mockData != null &&
(mockData[TYPENAME_KEY] == null ||
mockData[TYPENAME_KEY] === DEFAULT_MOCK_TYPENAME)
) {
mockData[TYPENAME_KEY] =
defaultValues?.[TYPENAME_KEY] ?? selection.type;
}
// Now, we need to make sure that we don't select abstract type
// for inline fragments
if (
isAbstractType === true &&
mockData != null &&
mockData[TYPENAME_KEY] === typeName
) {
mockData[TYPENAME_KEY] = selection.type;
}
if (mockData != null && mockData[TYPENAME_KEY] === selection.type) {
// This will get default values for current selection type
const defaults = this._getDefaultValuesForObject(
selection.type,
path[path.length - 1],
null,
path,
);
// Also, if the selection has an abstract type
// we may have mock resolvers for it
const defaultsForAbstractType =
typeName !== selection.type
? this._getDefaultValuesForObject(
typeName,
path[path.length - 1],
null,
path,
)
: defaults;
// Now let's select which defaults we're going to use
// for the selections
let defaultValuesForSelection = defaults; // First, defaults for
// concrete type of the selection
if (defaultValuesForSelection === undefined) {
// Second, defaults for abstract type of the selection
defaultValuesForSelection = defaultsForAbstractType;
}
// And last, values from the parent mock resolver
if (defaultValuesForSelection === undefined) {
defaultValuesForSelection = defaultValues;
}
// Now, if the default value for the type is explicit null,
// we may skip traversing child selection
if (defaultValuesForSelection === null) {
mockData = null;
break;
}
mockData = this._traverseSelections(
selection.selections,
selection.type,
isAbstractType,
path,
mockData,
defaultValuesForSelection,
);
if (mockData[TYPENAME_KEY] != null) {
mockData[TYPENAME_KEY] = selection.type;
}
// Make sure we're using id form the default values, an
// ID may be referenced in the same selection as InlineFragment
if (
mockData.id != null &&
defaults != null &&
defaults.id != null
) {
mockData.id = defaults.id;
}
}
break;
}
case MODULE_IMPORT:
// Explicit `null` of `defaultValues` handled in the INLINE_FRAGMENT
if (defaultValues != null) {
if (defaultValues.__typename !== typeName) {
break;
}
// In order to mock 3d payloads, we need to receive an object with
// the type `NormalizationSplitOperation` from mock resolvers.
// In this case, we can traverse into its selection
// and generated payloads for it.
const operation = defaultValues.__module_operation;
// Basic sanity checks of the provided default value.
// It should look like NormalizationSplitOperation
invariant(
typeof operation === 'object' &&
operation !== null &&
operation.kind === 'SplitOperation' &&
Array.isArray(operation.selections) &&
typeof operation.name === 'string',
'RelayMockPayloadGenerator(): Unexpected default value for ' +
'a field `__module_operation` in the mock resolver for ' +
'@module dependency. Provided value is "%s" and we\'re ' +
'expecting an object of a type `NormalizationSplitOperation`. ' +
'Please adjust mock resolver for the type "%s". ' +
'Typically it should require a file "%s$normalization.graphql".',
JSON.stringify(operation),
typeName,
selection.fragmentName,
);
const splitOperation: NormalizationSplitOperation =
operation as $FlowFixMe;
const {documentName} = selection;
if (mockData == null) {
mockData = {};
}
mockData = {
...mockData,
[TYPENAME_KEY]: typeName,
// $FlowFixMe[invalid-computed-prop]
[getModuleOperationKey(documentName)]: operation.name,
// $FlowFixMe[invalid-computed-prop]
[getModuleComponentKey(documentName)]:
defaultValues.__module_component,
...this._traverseSelections(
splitOperation.selections,
typeName,
false,
path,
null,
defaultValues,
),
};
}
break;
case TYPE_DISCRIMINATOR:
const {abstractKey} = selection;
if (mockData != null) {
mockData[abstractKey] = true;
}
break;
case SCALAR_HANDLE:
case LINKED_HANDLE:
break;
case ACTOR_CHANGE:
throw new Error('ActorChange fields are not yet supported.');
case RELAY_LIVE_RESOLVER:
case RELAY_RESOLVER:
if (selection.fragment) {
mockData = this._traverseSelections(
selection.fragment.selections,
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
}
break;
case CLIENT_EDGE_TO_CLIENT_OBJECT:
case CLIENT_EDGE_TO_SERVER_OBJECT:
mockData = this._traverseSelections(
[selection.backingField],
typeName,
isAbstractType,
path,
mockData,
defaultValues,
);
break;
default:
selection as empty;
invariant(
false,
'RelayMockPayloadGenerator(): Unexpected AST kind `%s`.',
selection.kind,
);
}
});
// $FlowFixMe[incompatible-type]
return mockData;
}
/**
* Generate default enum value
* @private
*/
_getCorrectDefaultEnum(
enumValues: ReadonlyArray<string>,
value: unknown | Array<unknown>,
path: ReadonlyArray<string>,
applicationName: string,
): ?(string | Array<string>) {
if (value === undefined) {
return value;
}
if (value === null) {
// null is a valid enum value
return value;
}
const valueToValidate = Array.isArray(value)
? value.map(v => String(v).toUpperCase())
: [String(value).toUpperCase()];
const enumValuesNormalized = enumValues.map(s => s.toUpperCase());
// Let's validate the correctness of the provided enum value
// We will throw if value provided by mock resolvers is invalid
const correctValues = valueToValidate.filter(v =>
enumValuesNormalized.includes(v),
);
if (correctValues.length !== valueToValidate.length) {
invariant(
false,
'RelayMockPayloadGenerator: Invalid value "%s" provided for enum ' +
'field "%s" via MockResolver.' +
'Expected one of the following values: %s.',
value,
`${path.join('.')}.${applicationName}`,
enumValues.map(v => `"${v}"`).join(', '),
);
}
// But missing case should be acceptable, we will just use
// a correct spelling from enumValues
const correctSpellingValues = valueToValidate.map(v => {
const correctSpellingEnumIndex = enumValuesNormalized.indexOf(
String(v).toUpperCase(),
);
return enumValues[correctSpellingEnumIndex];
});
return Array.isArray(value)
? correctSpellingValues
: correctSpellingValues[0];
}
/**
* Generate mock value for a scalar field in the selection
*/
_mockScalar(
field: NormalizationScalarField,
typeName: ?string,
path: ReadonlyArray<string>,
mockData: ?MockData,
defaultValues: ?MockData,
): MockData {
const data = mockData ?? ({} as {[string]: unknown});
const applicationName = field.alias ?? field.name;
if (data.hasOwnProperty(applicationName) && field.name !== TYPENAME_KEY) {
return data;
}
let value: unknown;
// For __typename fields we are going to return typeName
if (field.name === TYPENAME_KEY) {
value = typeName ?? DEFAULT_MOCK_TYPENAME;
}
const selectionPath = [...path, applicationName];
const {type, plural, enumValues} = this._getScalarFieldTypeDetails(
field,
typeName,
selectionPath,
);
// We may have an object with default values (generated in _mockLink(...))
// let's check if we have a possible default value there for our field
if (
defaultValues != null &&
defaultValues.hasOwnProperty(applicationName)
) {
value = defaultValues[applicationName];
if (enumValues != null) {
value = this._getCorrectDefaultEnum(
enumValues,
value,
path,
applicationName,
);
}
// And if it's a plural field, we need to return an array
if (value !== undefined && plural && !Array.isArray(value)) {
value = [value];
}
}
// If the value has not been generated yet (__id, __typename fields, or defaults)
// then we need to generate mock value for a scalar type
if (value === undefined) {
// Get basic type information: type of the field (Int, Float, String, etc..)
// And check if it's a plural type
const defaultValue = enumValues != null ? enumValues[0] : undefined;
value = this._resolveValue(
// If we don't have schema let's assume that fields with name (id, __id)
// have type ID
type,
{
parentType: typeName,
name: field.name,
alias: field.alias,
path: selectionPath,
args: this._getFieldArgs(field),
},
plural,
defaultValue,
);
}
data[applicationName] = value;
return data;
}
/**
* Generate mock data for linked fields in the selection
*/
_mockLink(
field: NormalizationLinkedField,
path: ReadonlyArray<string>,
prevData: ?MockData,
defaultValues: ?MockData,
): MockData | null {
const applicationName = field.alias ?? field.name;
const data: MockData = prevData ?? {};
const args = this._getFieldArgs(field);
// Let's check if we have a custom mock resolver for the object type
// We will pass this data down to selection, so _mockScalar(...) can use
// values from `defaults`
const selectionPath = [...path, applicationName];
const typeFromSelection = this._getTypeDetailsForPath(selectionPath) ?? {
type: DEFAULT_MOCK_TYPENAME,
};
let defaults;
if (
defaultValues != null &&
typeof defaultValues[applicationName] === 'object'
) {
defaults = defaultValues[applicationName];
}
// In cases when we have explicit `null` in the defaults - let's return
// null for full branch
if (defaults === null) {
data[applicationName] = null;
return data;
}
// If concrete type is null, let's try to get if from defaults,
// and fallback to default object type
const typeName =
field.concreteType ??
(defaults != null && typeof defaults[TYPENAME_KEY] === 'string'
? defaults[TYPENAME_KEY]
: typeFromSelection.type);
// Let's assume, that if the concrete type is null and selected type name is
// different from type information form selection, most likely this type
// information came from mock resolver __typename value and it was
// an intentional selection of the specific type
const isAbstractType =
field.concreteType == null && typeName === typeFromSelection.type;
const generateDataForField = (
possibleDefaultValue: unknown,
index?: number,
) => {
const fieldPath = field.plural
? [...selectionPath, index?.toString(10) ?? '0']
: selectionPath;
const fieldDefaultValue =
this._getDefaultValuesForObject(
field.concreteType ?? typeFromSelection.type,
field.name,
field.alias,
fieldPath,
args,
) ?? possibleDefaultValue;
if (fieldDefaultValue === null) {
return null;
}
// `fieldPath` above already indexes plural fields by `index`; the prior
// data must be indexed the same way, or the whole array is passed as each
// element's previous value and the list double-nests (`[[item]]`).
const prevFieldData = field.plural
? index != null && Array.isArray(data[applicationName])
? data[applicationName][index]
: null
: data[applicationName];
return this._traverse(
{
selections: field.selections,
typeName,
isAbstractType: isAbstractType,
name: field.name,
alias: field.alias,
args,
},
fieldPath,
typeof prevFieldData === 'object' && prevFieldData !== null
? // $FlowFixMe[incompatible-variance]
prevFieldData
: null,
// $FlowFixMe[incompatible-type]
fieldDefaultValue,
);
};
data[applicationName] =
field.kind === 'LinkedField' && field.plural
? generateMockList(
Array.isArray(defaults) ? defaults : Array(1).fill(),
generateDataForField,
)
: generateDataForField(defaults);
return data;
}
/**
* Get the value for a variable by name
*/
_getVariableValue(name: string): unknown {
invariant(
this._variables.hasOwnProperty(name),
'RelayMockPayloadGenerator(): Undefined variable `%s`.',
name,
);
return this._variables[name];
}
/**
* This method should call mock resolver for a specific type name
* and the result of this mock resolver will be passed as a default values for
* _mock*(...) methods
*/
_getDefaultValuesForObject(
typeName: ?string,
fieldName: ?string,
fieldAlias: ?string,
path: ReadonlyArray<string>,
args: ?{[string]: unknown, ...},
): ?MockData {
let data;
if (typeName != null && this._mockResolvers[typeName] != null) {
data = this._resolveValue(
typeName,
{
parentType: null,
name: fieldName,
alias: fieldAlias,
args,
path,
},
false,
);
}
if (typeof data === 'object') {
// $FlowFixMe[incompatible-variance]
return data;
}
}
/**
* Get object with variables for field
*/
_getFieldArgs(field: NormalizationField): {[string]: unknown, ...} {
const args: {[string]: unknown} = {};
if (field.args != null) {
field.args.forEach(arg => {
args[arg.name] = this._getArgValue(arg);
});
}
return args;
}
_getArgValue(arg: NormalizationArgument): unknown {
switch (arg.kind) {
case 'Literal':
return arg.value;
case 'Variable':
return this._getVariableValue(arg.variableName);
case 'ObjectValue': {
const value: {[string]: unknown} = {};
arg.fields.forEach(field => {
value[field.name] = this._getArgValue(field);
});
return value;
}
case 'ListValue': {
const value = [];
arg.items.forEach(item => {
value.push(item != null ? this._getArgValue(item) : null);
});
return value;
}
}
}
/**
* Helper function to get field type information (name of the type, plural)
*/
_getScalarFieldTypeDetails(
field: NormalizationScalarField,
typeName: ?string,
selectionPath: ReadonlyArray<string>,
): {
readonly type: string,
readonly plural: boolean,
readonly enumValues: ReadonlyArray<string> | null,
readonly nullable: boolean,
} {
return (
this._getTypeDetailsForPath(selectionPath) ?? {
type: field.name === 'id' ? 'ID' : 'String',
plural: false,
enumValues: null,
nullable: false,
}
);
}
/**
* When selecting metadata, skip the number on plural fields so that every field in the array
* gets the same metadata.
* @private
*/
_getTypeDetailsForPath(
path: ReadonlyArray<string>,
): Values<SelectionMetadata> {
return this._selectionMetadata[
// When selecting metadata, skip the number on plural fields so that every field in the array
// gets the same metadata.
path.filter(field => isNaN(parseInt(field, 10))).join('.')
];
}
}
/**
* Generate mock data for NormalizationOperation selection
*/
function generateData(
node: NormalizationOperation,
variables: Variables,
mockResolvers: MockResolvers | null,
selectionMetadata: SelectionMetadata | null,
options: ?{mockClientData?: boolean, generateDeferredPayload?: boolean},
): Array<GraphQLSingularResponse> {
const mockGenerator = new RelayMockPayloadGenerator({
variables,
mockResolvers,
selectionMetadata,
mockClientData: options?.mockClientData,
generateDeferredPayload: options?.generateDeferredPayload,
});
let operationType;
if (node.name.endsWith('Mutation')) {
operationType = 'Mutation';
} else if (node.name.endsWith('Subscription')) {
operationType = 'Subscription';
} else {
operationType = 'Query';
}
return mockGenerator.generate(node.selections, operationType);
}
/**
* Type refinement for selection metadata
*/
function getSelectionMetadataFromOperation(