-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ValuesResolver.java
959 lines (867 loc) · 43.7 KB
/
ValuesResolver.java
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
package graphql.execution;
import com.google.common.collect.ImmutableList;
import graphql.AssertException;
import graphql.Internal;
import graphql.Scalars;
import graphql.VisibleForTesting;
import graphql.language.Argument;
import graphql.language.ArrayValue;
import graphql.language.BooleanValue;
import graphql.language.EnumValue;
import graphql.language.FloatValue;
import graphql.language.IntValue;
import graphql.language.NullValue;
import graphql.language.ObjectField;
import graphql.language.ObjectValue;
import graphql.language.StringValue;
import graphql.language.Value;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import graphql.normalized.NormalizedInputValue;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLCodeRegistry;
import graphql.schema.GraphQLEnumType;
import graphql.schema.GraphQLInputObjectField;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLInputType;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import graphql.schema.GraphQLTypeUtil;
import graphql.schema.InputValueWithState;
import graphql.schema.PropertyDataFetcherHelper;
import graphql.schema.visibility.DefaultGraphqlFieldVisibility;
import graphql.schema.visibility.GraphqlFieldVisibility;
import graphql.util.FpKit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static graphql.Assert.assertShouldNeverHappen;
import static graphql.Assert.assertTrue;
import static graphql.collect.ImmutableKit.emptyList;
import static graphql.collect.ImmutableKit.emptyMap;
import static graphql.collect.ImmutableKit.map;
import static graphql.execution.ValuesResolver.ValueMode.NORMALIZED;
import static graphql.language.NullValue.newNullValue;
import static graphql.language.ObjectField.newObjectField;
import static graphql.schema.GraphQLTypeUtil.isList;
import static graphql.schema.GraphQLTypeUtil.isNonNull;
import static graphql.schema.GraphQLTypeUtil.simplePrint;
import static graphql.schema.GraphQLTypeUtil.unwrapNonNull;
import static graphql.schema.GraphQLTypeUtil.unwrapOne;
import static graphql.schema.visibility.DefaultGraphqlFieldVisibility.DEFAULT_FIELD_VISIBILITY;
import static java.util.stream.Collectors.toList;
@SuppressWarnings("rawtypes")
@Internal
public class ValuesResolver {
public enum ValueMode {
LITERAL,
NORMALIZED
}
/**
* This method coerces the "raw" variables values provided to the engine. The coerced values will be used to
* provide arguments to {@link graphql.schema.DataFetchingEnvironment}
*
* This method is called once per execution and also performs validation.
*
* @param schema the schema
* @param variableDefinitions the variable definitions
* @param rawVariables the supplied variables
*
* @return coerced variable values as a map
*/
public CoercedVariables coerceVariableValues(GraphQLSchema schema,
List<VariableDefinition> variableDefinitions,
RawVariables rawVariables) throws CoercingParseValueException, NonNullableValueCoercedAsNullException {
return externalValueToInternalValueForVariables(schema, variableDefinitions, rawVariables);
}
/**
* Normalized variables values are Literals with type information. No validation here!
*
* @param schema the schema to use
* @param variableDefinitions the list of variable definitions
* @param rawVariables the raw variables
*
* @return a map of the normalised values
*/
public Map<String, NormalizedInputValue> getNormalizedVariableValues(GraphQLSchema schema,
List<VariableDefinition> variableDefinitions,
RawVariables rawVariables) {
GraphqlFieldVisibility fieldVisibility = schema.getCodeRegistry().getFieldVisibility();
Map<String, NormalizedInputValue> result = new LinkedHashMap<>();
for (VariableDefinition variableDefinition : variableDefinitions) {
String variableName = variableDefinition.getName();
GraphQLType variableType = TypeFromAST.getTypeFromAST(schema, variableDefinition.getType());
assertTrue(variableType instanceof GraphQLInputType);
// can be NullValue
Value defaultValue = variableDefinition.getDefaultValue();
boolean hasValue = rawVariables.containsKey(variableName);
Object value = rawVariables.get(variableName);
if (!hasValue && defaultValue != null) {
result.put(variableName, new NormalizedInputValue(simplePrint(variableType), defaultValue));
} else if (isNonNull(variableType) && (!hasValue || value == null)) {
return assertShouldNeverHappen("variable values are expected to be valid");
} else if (hasValue) {
if (value == null) {
result.put(variableName, new NormalizedInputValue(simplePrint(variableType), null));
} else {
Object literal = externalValueToLiteral(fieldVisibility, value, (GraphQLInputType) variableType, NORMALIZED);
result.put(variableName, new NormalizedInputValue(simplePrint(variableType), literal));
}
}
}
return result;
}
/**
* This is not used for validation: the argument literals are all validated and the variables are validated (when coerced)
*
* @param argumentTypes the list of argument types
* @param arguments the AST arguments
* @param coercedVariables the coerced variables
*
* @return a map of named argument values
*/
public Map<String, Object> getArgumentValues(List<GraphQLArgument> argumentTypes,
List<Argument> arguments,
CoercedVariables coercedVariables) {
return getArgumentValuesImpl(DEFAULT_FIELD_VISIBILITY, argumentTypes, arguments, coercedVariables);
}
/**
* No validation as the arguments are assumed valid
*
* @param argumentTypes the list of argument types
* @param arguments the AST arguments
* @param normalizedVariables the normalised variables
*
* @return a map of named normalised values
*/
public Map<String, NormalizedInputValue> getNormalizedArgumentValues(List<GraphQLArgument> argumentTypes,
List<Argument> arguments,
Map<String, NormalizedInputValue> normalizedVariables) {
if (argumentTypes.isEmpty()) {
return Collections.emptyMap();
}
Map<String, NormalizedInputValue> result = new LinkedHashMap<>();
Map<String, Argument> argumentMap = argumentMap(arguments);
for (GraphQLArgument argumentDefinition : argumentTypes) {
String argumentName = argumentDefinition.getName();
Argument argument = argumentMap.get(argumentName);
if (argument == null) {
continue;
}
// If a variable doesn't exist then we can't put it into the result Map
if (isVariableAbsent(argument.getValue(), normalizedVariables)) {
continue;
}
GraphQLInputType argumentType = argumentDefinition.getType();
Object value = literalToNormalizedValue(DEFAULT_FIELD_VISIBILITY, argumentType, argument.getValue(), normalizedVariables);
result.put(argumentName, new NormalizedInputValue(simplePrint(argumentType), value));
}
return result;
}
public Map<String, Object> getArgumentValues(GraphQLCodeRegistry codeRegistry,
List<GraphQLArgument> argumentTypes,
List<Argument> arguments,
CoercedVariables coercedVariables) {
return getArgumentValuesImpl(codeRegistry.getFieldVisibility(), argumentTypes, arguments, coercedVariables);
}
public static Value<?> valueToLiteral(InputValueWithState inputValueWithState, GraphQLType type) {
return valueToLiteral(DEFAULT_FIELD_VISIBILITY, inputValueWithState, type);
}
/**
* Takes a value which can be in different states (internal, literal, external value) and converts into Literal
*
* This assumes the value is valid!
*
* @param fieldVisibility the field visibility to use
* @param inputValueWithState the input value
* @param type the type of input value
*
* @return a value converted to a literal
*/
public static Value<?> valueToLiteral(@NotNull GraphqlFieldVisibility fieldVisibility, @NotNull InputValueWithState inputValueWithState, @NotNull GraphQLType type) {
return (Value<?>) valueToLiteral(fieldVisibility, inputValueWithState, type, ValueMode.LITERAL);
}
private static Object valueToLiteral(GraphqlFieldVisibility fieldVisibility, InputValueWithState inputValueWithState, GraphQLType type, ValueMode valueMode) {
if (inputValueWithState.isInternal()) {
if (valueMode == NORMALIZED) {
return assertShouldNeverHappen("can't infer normalized structure");
}
return valueToLiteralLegacy(inputValueWithState.getValue(), type);
}
if (inputValueWithState.isLiteral()) {
return inputValueWithState.getValue();
}
if (inputValueWithState.isExternal()) {
return new ValuesResolver().externalValueToLiteral(fieldVisibility, inputValueWithState.getValue(), (GraphQLInputType) type, valueMode);
}
return assertShouldNeverHappen("unexpected value state " + inputValueWithState);
}
/**
* Converts an external value to an internal value
*
* @param fieldVisibility the field visibility to use
* @param externalValue the input external value
* @param type the type of input value
*
* @return a value converted to an internal value
*/
public static Object externalValueToInternalValue(GraphqlFieldVisibility fieldVisibility, Object externalValue, GraphQLInputType type) {
return new ValuesResolver().externalValueToInternalValue(fieldVisibility, type, externalValue);
}
public static Object valueToInternalValue(InputValueWithState inputValueWithState, GraphQLType type) throws CoercingParseValueException, CoercingParseLiteralException {
DefaultGraphqlFieldVisibility fieldVisibility = DEFAULT_FIELD_VISIBILITY;
if (inputValueWithState.isInternal()) {
return inputValueWithState.getValue();
}
if (inputValueWithState.isLiteral()) {
return new ValuesResolver().literalToInternalValue(fieldVisibility, type, (Value<?>) inputValueWithState.getValue(), CoercedVariables.emptyVariables());
}
if (inputValueWithState.isExternal()) {
return new ValuesResolver().externalValueToInternalValue(fieldVisibility, type, inputValueWithState.getValue());
}
return assertShouldNeverHappen("unexpected value state " + inputValueWithState);
}
@Nullable
@SuppressWarnings("unchecked")
public static <T> T getInputValueImpl(GraphQLInputType inputType, InputValueWithState inputValue) {
if (inputValue.isNotSet()) {
return null;
}
return (T) valueToInternalValue(inputValue, inputType);
}
/**
* No validation: the external value is assumed to be valid.
*/
private Object externalValueToLiteral(GraphqlFieldVisibility fieldVisibility,
@Nullable Object value,
GraphQLInputType type,
ValueMode valueMode
) {
if (value == null) {
return newNullValue().build();
}
if (GraphQLTypeUtil.isNonNull(type)) {
return externalValueToLiteral(fieldVisibility, value, (GraphQLInputType) unwrapNonNull(type), valueMode);
}
if (type instanceof GraphQLScalarType) {
return externalValueToLiteralForScalar((GraphQLScalarType) type, value);
} else if (type instanceof GraphQLEnumType) {
return externalValueToLiteralForEnum((GraphQLEnumType) type, value);
} else if (type instanceof GraphQLList) {
return externalValueToLiteralForList(fieldVisibility, (GraphQLList) type, value, valueMode);
} else if (type instanceof GraphQLInputObjectType) {
return externalValueToLiteralForObject(fieldVisibility, (GraphQLInputObjectType) type, value, valueMode);
} else {
return assertShouldNeverHappen("unexpected type %s", type);
}
}
/**
* No validation
*/
private Value externalValueToLiteralForScalar(GraphQLScalarType scalarType, Object value) {
return scalarType.getCoercing().valueToLiteral(value);
}
/**
* No validation
*/
private Value externalValueToLiteralForEnum(GraphQLEnumType enumType, Object value) {
return enumType.valueToLiteral(value);
}
/**
* No validation
*/
@SuppressWarnings("unchecked")
private Object externalValueToLiteralForList(GraphqlFieldVisibility fieldVisibility, GraphQLList listType, Object value, ValueMode valueMode) {
GraphQLInputType wrappedType = (GraphQLInputType) listType.getWrappedType();
List result = FpKit.toListOrSingletonList(value)
.stream()
.map(val -> externalValueToLiteral(fieldVisibility, val, wrappedType, valueMode))
.collect(toList());
if (valueMode == NORMALIZED) {
return result;
} else {
return ArrayValue.newArrayValue().values(result).build();
}
}
/**
* No validation
*/
@SuppressWarnings("unchecked")
private Object externalValueToLiteralForObject(GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType inputObjectType,
Object inputValue,
ValueMode valueMode) {
assertTrue(inputValue instanceof Map, () -> "Expect Map as input");
Map<String, Object> inputMap = (Map<String, Object>) inputValue;
List<GraphQLInputObjectField> fieldDefinitions = fieldVisibility.getFieldDefinitions(inputObjectType);
Map<String, Object> normalizedResult = new LinkedHashMap<>();
ImmutableList.Builder<ObjectField> objectFields = ImmutableList.builder();
for (GraphQLInputObjectField inputFieldDefinition : fieldDefinitions) {
GraphQLInputType fieldType = inputFieldDefinition.getType();
String fieldName = inputFieldDefinition.getName();
boolean hasValue = inputMap.containsKey(fieldName);
Object fieldValue = inputMap.getOrDefault(fieldName, null);
if (!hasValue && inputFieldDefinition.hasSetDefaultValue()) {
//TODO: consider valueMode
Object defaultValueLiteral = valueToLiteral(fieldVisibility, inputFieldDefinition.getInputFieldDefaultValue(), fieldType);
if (valueMode == ValueMode.LITERAL) {
normalizedResult.put(fieldName, new NormalizedInputValue(simplePrint(fieldType), defaultValueLiteral));
} else {
objectFields.add(newObjectField().name(fieldName).value((Value) defaultValueLiteral).build());
}
} else if (hasValue) {
if (fieldValue == null) {
if (valueMode == NORMALIZED) {
normalizedResult.put(fieldName, new NormalizedInputValue(simplePrint(fieldType), null));
} else {
objectFields.add(newObjectField().name(fieldName).value(newNullValue().build()).build());
}
} else {
Object literal = externalValueToLiteral(fieldVisibility,
fieldValue,
fieldType,
valueMode);
if (valueMode == NORMALIZED) {
normalizedResult.put(fieldName, new NormalizedInputValue(simplePrint(fieldType), literal));
} else {
objectFields.add(newObjectField().name(fieldName).value((Value) literal).build());
}
}
}
}
if (valueMode == NORMALIZED) {
return normalizedResult;
}
return ObjectValue.newObjectValue().objectFields(objectFields.build()).build();
}
/**
* performs validation too
*/
private CoercedVariables externalValueToInternalValueForVariables(GraphQLSchema schema,
List<VariableDefinition> variableDefinitions,
RawVariables rawVariables) {
GraphqlFieldVisibility fieldVisibility = schema.getCodeRegistry().getFieldVisibility();
Map<String, Object> coercedValues = new LinkedHashMap<>();
for (VariableDefinition variableDefinition : variableDefinitions) {
try {
String variableName = variableDefinition.getName();
GraphQLType variableType = TypeFromAST.getTypeFromAST(schema, variableDefinition.getType());
assertTrue(variableType instanceof GraphQLInputType);
// can be NullValue
Value defaultValue = variableDefinition.getDefaultValue();
boolean hasValue = rawVariables.containsKey(variableName);
Object value = rawVariables.get(variableName);
if (!hasValue && defaultValue != null) {
Object coercedDefaultValue = literalToInternalValue(fieldVisibility, variableType, defaultValue, CoercedVariables.emptyVariables());
coercedValues.put(variableName, coercedDefaultValue);
} else if (isNonNull(variableType) && (!hasValue || value == null)) {
throw new NonNullableValueCoercedAsNullException(variableDefinition, variableType);
} else if (hasValue) {
if (value == null) {
coercedValues.put(variableName, null);
} else {
Object coercedValue = externalValueToInternalValue(fieldVisibility, variableType, value);
coercedValues.put(variableName, coercedValue);
}
}
} catch (CoercingParseValueException e) {
throw CoercingParseValueException.newCoercingParseValueException()
.message(String.format("Variable '%s' has an invalid value: %s", variableDefinition.getName(), e.getMessage()))
.extensions(e.getExtensions())
.cause(e.getCause())
.sourceLocation(variableDefinition.getSourceLocation())
.build();
} catch (NonNullableValueCoercedAsNullException e) {
throw new NonNullableValueCoercedAsNullException(variableDefinition, e.getMessage());
}
}
return CoercedVariables.of(coercedValues);
}
private Map<String, Object> getArgumentValuesImpl(GraphqlFieldVisibility fieldVisibility,
List<GraphQLArgument> argumentTypes,
List<Argument> arguments,
CoercedVariables coercedVariables) {
if (argumentTypes.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> coercedValues = new LinkedHashMap<>();
Map<String, Argument> argumentMap = argumentMap(arguments);
for (GraphQLArgument argumentDefinition : argumentTypes) {
GraphQLInputType argumentType = argumentDefinition.getType();
String argumentName = argumentDefinition.getName();
Argument argument = argumentMap.get(argumentName);
InputValueWithState defaultValue = argumentDefinition.getArgumentDefaultValue();
boolean hasValue = argument != null;
Object value;
Value argumentValue = argument != null ? argument.getValue() : null;
if (argumentValue instanceof VariableReference) {
String variableName = ((VariableReference) argumentValue).getName();
hasValue = coercedVariables.containsKey(variableName);
value = coercedVariables.get(variableName);
} else {
value = argumentValue;
}
if (!hasValue && argumentDefinition.hasSetDefaultValue()) {
Object coercedDefaultValue = defaultValueToInternalValue(
fieldVisibility,
defaultValue,
argumentType);
coercedValues.put(argumentName, coercedDefaultValue);
} else if (isNonNull(argumentType) && (!hasValue || isNullValue(value))) {
throw new NonNullableValueCoercedAsNullException(argumentDefinition);
} else if (hasValue) {
if (isNullValue(value)) {
coercedValues.put(argumentName, value);
} else if (argumentValue instanceof VariableReference) {
coercedValues.put(argumentName, value);
} else {
value = literalToInternalValue(fieldVisibility, argumentType, argument.getValue(), coercedVariables);
coercedValues.put(argumentName, value);
}
}
}
return coercedValues;
}
private Map<String, Argument> argumentMap(List<Argument> arguments) {
Map<String, Argument> result = new LinkedHashMap<>(arguments.size());
for (Argument argument : arguments) {
result.put(argument.getName(), argument);
}
return result;
}
/**
* Performs validation too
*/
@SuppressWarnings("unchecked")
private Object externalValueToInternalValue(GraphqlFieldVisibility fieldVisibility,
GraphQLType graphQLType,
Object value) throws NonNullableValueCoercedAsNullException, CoercingParseValueException {
if (isNonNull(graphQLType)) {
Object returnValue =
externalValueToInternalValue(fieldVisibility, unwrapOne(graphQLType), value);
if (returnValue == null) {
throw new NonNullableValueCoercedAsNullException(graphQLType);
}
return returnValue;
}
if (value == null) {
return null;
}
if (graphQLType instanceof GraphQLScalarType) {
return externalValueToInternalValueForScalar((GraphQLScalarType) graphQLType, value);
} else if (graphQLType instanceof GraphQLEnumType) {
return externalValueToInternalValueForEnum((GraphQLEnumType) graphQLType, value);
} else if (graphQLType instanceof GraphQLList) {
return externalValueToInternalValueForList(fieldVisibility, (GraphQLList) graphQLType, value);
} else if (graphQLType instanceof GraphQLInputObjectType) {
if (value instanceof Map) {
return externalValueToInternalValueForObject(fieldVisibility, (GraphQLInputObjectType) graphQLType, (Map<String, Object>) value);
} else {
throw CoercingParseValueException.newCoercingParseValueException()
.message("Expected type 'Map' but was '" + value.getClass().getSimpleName() +
"'. Variables for input objects must be an instance of type 'Map'.")
.build();
}
} else {
return assertShouldNeverHappen("unhandled type %s", graphQLType);
}
}
/**
* performs validation
*/
private Object externalValueToInternalValueForObject(GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType inputObjectType,
Map<String, Object> inputMap
) throws NonNullableValueCoercedAsNullException, CoercingParseValueException {
List<GraphQLInputObjectField> fieldDefinitions = fieldVisibility.getFieldDefinitions(inputObjectType);
List<String> fieldNames = map(fieldDefinitions, GraphQLInputObjectField::getName);
for (String providedFieldName : inputMap.keySet()) {
if (!fieldNames.contains(providedFieldName)) {
throw new InputMapDefinesTooManyFieldsException(inputObjectType, providedFieldName);
}
}
Map<String, Object> coercedValues = new LinkedHashMap<>();
for (GraphQLInputObjectField inputFieldDefinition : fieldDefinitions) {
GraphQLInputType fieldType = inputFieldDefinition.getType();
String fieldName = inputFieldDefinition.getName();
InputValueWithState defaultValue = inputFieldDefinition.getInputFieldDefaultValue();
boolean hasValue = inputMap.containsKey(fieldName);
Object value;
Object fieldValue = inputMap.getOrDefault(fieldName, null);
value = fieldValue;
if (!hasValue && inputFieldDefinition.hasSetDefaultValue()) {
Object coercedDefaultValue = defaultValueToInternalValue(fieldVisibility,
defaultValue,
fieldType);
coercedValues.put(fieldName, coercedDefaultValue);
} else if (isNonNull(fieldType) && (!hasValue || value == null)) {
throw new NonNullableValueCoercedAsNullException(fieldName, emptyList(), fieldType);
} else if (hasValue) {
if (value == null) {
coercedValues.put(fieldName, null);
} else {
value = externalValueToInternalValue(fieldVisibility,
fieldType, value);
coercedValues.put(fieldName, value);
}
}
}
return coercedValues;
}
/**
* including validation
*/
private Object externalValueToInternalValueForScalar(GraphQLScalarType graphQLScalarType, Object value) throws CoercingParseValueException {
return graphQLScalarType.getCoercing().parseValue(value);
}
/**
* including validation
*/
private Object externalValueToInternalValueForEnum(GraphQLEnumType graphQLEnumType, Object value) throws CoercingParseValueException {
return graphQLEnumType.parseValue(value);
}
/**
* including validation
*/
private List externalValueToInternalValueForList(GraphqlFieldVisibility fieldVisibility,
GraphQLList graphQLList,
Object value
) throws CoercingParseValueException, NonNullableValueCoercedAsNullException {
GraphQLType wrappedType = graphQLList.getWrappedType();
return FpKit.toListOrSingletonList(value)
.stream()
.map(val -> externalValueToInternalValue(fieldVisibility, wrappedType, val))
.collect(toList());
}
public Object literalToNormalizedValue(GraphqlFieldVisibility fieldVisibility,
GraphQLType type,
Value inputValue,
Map<String, NormalizedInputValue> normalizedVariables
) {
if (inputValue instanceof VariableReference) {
String varName = ((VariableReference) inputValue).getName();
return normalizedVariables.get(varName).getValue();
}
if (inputValue instanceof NullValue) {
return null;
}
if (type instanceof GraphQLScalarType) {
return inputValue;
}
if (isNonNull(type)) {
return literalToNormalizedValue(fieldVisibility, unwrapOne(type), inputValue, normalizedVariables);
}
if (type instanceof GraphQLInputObjectType) {
return literalToNormalizedValueForInputObject(fieldVisibility, (GraphQLInputObjectType) type, (ObjectValue) inputValue, normalizedVariables);
}
if (type instanceof GraphQLEnumType) {
return inputValue;
}
if (isList(type)) {
return literalToNormalizedValueForList(fieldVisibility, (GraphQLList) type, inputValue, normalizedVariables);
}
return null;
}
private Object literalToNormalizedValueForInputObject(GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType type,
ObjectValue inputObjectLiteral,
Map<String, NormalizedInputValue> normalizedVariables) {
Map<String, Object> result = new LinkedHashMap<>();
for (ObjectField field : inputObjectLiteral.getObjectFields()) {
// If a variable doesn't exist then we can't put it into the result Map
if (isVariableAbsent(field.getValue(), normalizedVariables)) {
continue;
}
GraphQLInputType fieldType = type.getField(field.getName()).getType();
Object fieldValue = literalToNormalizedValue(fieldVisibility, fieldType, field.getValue(), normalizedVariables);
result.put(field.getName(), new NormalizedInputValue(simplePrint(fieldType), fieldValue));
}
return result;
}
private List<Object> literalToNormalizedValueForList(GraphqlFieldVisibility fieldVisibility,
GraphQLList type,
Value value,
Map<String, NormalizedInputValue> normalizedVariables) {
if (value instanceof ArrayValue) {
List<Object> result = new ArrayList<>();
for (Value valueInArray : ((ArrayValue) value).getValues()) {
result.add(literalToNormalizedValue(fieldVisibility, type.getWrappedType(), valueInArray, normalizedVariables));
}
return result;
} else {
return Collections.singletonList(literalToNormalizedValue(fieldVisibility, type.getWrappedType(), value, normalizedVariables));
}
}
/**
* No validation (it was checked before via ArgumentsOfCorrectType and VariableDefaultValuesOfCorrectType)
*
* @param fieldVisibility the field visibility
* @param type the type of the input value
* @param inputValue the AST literal to be changed
* @param coercedVariables the coerced variable values
*
* @return literal converted to an internal value
*/
public Object literalToInternalValue(GraphqlFieldVisibility fieldVisibility,
GraphQLType type,
Value inputValue,
CoercedVariables coercedVariables) {
if (inputValue instanceof VariableReference) {
return coercedVariables.get(((VariableReference) inputValue).getName());
}
if (inputValue instanceof NullValue) {
return null;
}
if (type instanceof GraphQLScalarType) {
return literalToInternalValueForScalar(inputValue, (GraphQLScalarType) type, coercedVariables);
}
if (isNonNull(type)) {
return literalToInternalValue(fieldVisibility, unwrapOne(type), inputValue, coercedVariables);
}
if (type instanceof GraphQLInputObjectType) {
return literalToInternalValueForInputObject(fieldVisibility, (GraphQLInputObjectType) type, (ObjectValue) inputValue, coercedVariables);
}
if (type instanceof GraphQLEnumType) {
return ((GraphQLEnumType) type).parseLiteral(inputValue);
}
if (isList(type)) {
return literalToInternalValueForList(fieldVisibility, (GraphQLList) type, inputValue, coercedVariables);
}
return null;
}
/**
* no validation
*/
private Object literalToInternalValueForScalar(Value inputValue, GraphQLScalarType scalarType, CoercedVariables coercedVariables) {
// the CoercingParseLiteralException exception that could happen here has been validated earlier via ValidationUtil
return scalarType.getCoercing().parseLiteral(inputValue, coercedVariables.toMap());
}
/**
* no validation
*/
private Object literalToInternalValueForList(GraphqlFieldVisibility fieldVisibility,
GraphQLList graphQLList,
Value value,
CoercedVariables coercedVariables) {
if (value instanceof ArrayValue) {
ArrayValue arrayValue = (ArrayValue) value;
List<Object> result = new ArrayList<>();
for (Value singleValue : arrayValue.getValues()) {
result.add(literalToInternalValue(fieldVisibility, graphQLList.getWrappedType(), singleValue, coercedVariables));
}
return result;
} else {
return Collections.singletonList(
literalToInternalValue(fieldVisibility,
graphQLList.getWrappedType(),
value,
coercedVariables));
}
}
/**
* no validation
*/
private Object literalToInternalValueForInputObject(GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType type,
ObjectValue inputValue,
CoercedVariables coercedVariables) {
Map<String, Object> coercedValues = new LinkedHashMap<>();
Map<String, ObjectField> inputFieldsByName = mapObjectValueFieldsByName(inputValue);
List<GraphQLInputObjectField> inputFieldTypes = fieldVisibility.getFieldDefinitions(type);
for (GraphQLInputObjectField inputFieldDefinition : inputFieldTypes) {
GraphQLInputType fieldType = inputFieldDefinition.getType();
String fieldName = inputFieldDefinition.getName();
ObjectField field = inputFieldsByName.get(fieldName);
boolean hasValue = field != null;
Object value;
Value fieldValue = field != null ? field.getValue() : null;
if (fieldValue instanceof VariableReference) {
String variableName = ((VariableReference) fieldValue).getName();
hasValue = coercedVariables.containsKey(variableName);
value = coercedVariables.get(variableName);
} else {
value = fieldValue;
}
if (!hasValue && inputFieldDefinition.hasSetDefaultValue()) {
Object coercedDefaultValue = defaultValueToInternalValue(fieldVisibility,
inputFieldDefinition.getInputFieldDefaultValue(),
fieldType);
coercedValues.put(fieldName, coercedDefaultValue);
} else if (isNonNull(fieldType) && (!hasValue || isNullValue(value))) {
return assertShouldNeverHappen("Should have been validated before");
} else if (hasValue) {
if (isNullValue(value)) {
coercedValues.put(fieldName, value);
} else if (fieldValue instanceof VariableReference) {
coercedValues.put(fieldName, value);
} else {
value = literalToInternalValue(fieldVisibility, fieldType, fieldValue, coercedVariables);
coercedValues.put(fieldName, value);
}
}
}
return coercedValues;
}
private boolean isNullValue(Object value) {
if (value == null) {
return true;
}
if (!(value instanceof NormalizedInputValue)) {
return false;
}
return ((NormalizedInputValue) value).getValue() == null;
}
private Map<String, ObjectField> mapObjectValueFieldsByName(ObjectValue inputValue) {
Map<String, ObjectField> inputValueFieldsByName = new LinkedHashMap<>();
for (ObjectField objectField : inputValue.getObjectFields()) {
inputValueFieldsByName.put(objectField.getName(), objectField);
}
return inputValueFieldsByName;
}
private Object defaultValueToInternalValue(GraphqlFieldVisibility fieldVisibility,
InputValueWithState defaultValue,
GraphQLInputType type
) {
if (defaultValue.isInternal()) {
return defaultValue.getValue();
}
if (defaultValue.isLiteral()) {
// default value literals can't reference variables, this is why the variables are empty
return literalToInternalValue(fieldVisibility, type, (Value) defaultValue.getValue(), CoercedVariables.emptyVariables());
}
if (defaultValue.isExternal()) {
// performs validation too
return externalValueToInternalValue(fieldVisibility, type, defaultValue.getValue());
}
return assertShouldNeverHappen();
}
/*
* ======================LEGACY=======+TO BE REMOVED IN THE FUTURE ===============
*/
/**
* Legacy logic to convert an arbitrary java object to an Ast Literal.
* Only provided here to preserve backwards compatibility.
*/
@VisibleForTesting
static Value<?> valueToLiteralLegacy(Object value, GraphQLType type) {
assertTrue(!(value instanceof Value), () -> "Unexpected literal " + value);
if (value == null) {
return null;
}
if (isNonNull(type)) {
return handleNonNullLegacy(value, (GraphQLNonNull) type);
}
// Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
// the value is not an array, convert the value using the list's item type.
if (isList(type)) {
return handleListLegacy(value, (GraphQLList) type);
}
// Populate the fields of the input object by creating ASTs from each value
// in the JavaScript object according to the fields in the input type.
if (type instanceof GraphQLInputObjectType) {
return handleInputObjectLegacy(value, (GraphQLInputObjectType) type);
}
if (!(type instanceof GraphQLScalarType || type instanceof GraphQLEnumType)) {
throw new AssertException("Must provide Input Type, cannot use: " + type.getClass());
}
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
final Object serialized = serializeLegacy(type, value);
if (isNullishLegacy(serialized)) {
return null;
}
// Others serialize based on their corresponding JavaScript scalar types.
if (serialized instanceof Boolean) {
return BooleanValue.newBooleanValue().value((Boolean) serialized).build();
}
String stringValue = serialized.toString();
// numbers can be Int or Float values.
if (serialized instanceof Number) {
return handleNumberLegacy(stringValue);
}
if (serialized instanceof String) {
// Enum types use Enum literals.
if (type instanceof GraphQLEnumType) {
return EnumValue.newEnumValue().name(stringValue).build();
}
// ID types can use Int literals.
if (type == Scalars.GraphQLID && stringValue.matches("^[0-9]+$")) {
return IntValue.newIntValue().value(new BigInteger(stringValue)).build();
}
return StringValue.newStringValue().value(stringValue).build();
}
throw new AssertException("'Cannot convert value to AST: " + serialized);
}
private static Value<?> handleInputObjectLegacy(Object javaValue, GraphQLInputObjectType type) {
List<GraphQLInputObjectField> fields = type.getFields();
List<ObjectField> fieldNodes = new ArrayList<>();
fields.forEach(field -> {
String fieldName = field.getName();
GraphQLInputType fieldType = field.getType();
Object fieldValueObj = PropertyDataFetcherHelper.getPropertyValue(fieldName, javaValue, fieldType);
Value<?> nodeValue = valueToLiteralLegacy(fieldValueObj, fieldType);
if (nodeValue != null) {
fieldNodes.add(newObjectField().name(fieldName).value(nodeValue).build());
}
});
return ObjectValue.newObjectValue().objectFields(fieldNodes).build();
}
private static Value<?> handleNumberLegacy(String stringValue) {
if (stringValue.matches("^[0-9]+$")) {
return IntValue.newIntValue().value(new BigInteger(stringValue)).build();
} else {
return FloatValue.newFloatValue().value(new BigDecimal(stringValue)).build();
}
}
@SuppressWarnings("rawtypes")
private static Value<?> handleListLegacy(Object value, GraphQLList type) {
GraphQLType itemType = type.getWrappedType();
if (FpKit.isIterable(value)) {
List<Value> valuesNodes = FpKit.toListOrSingletonList(value)
.stream()
.map(item -> valueToLiteralLegacy(item, itemType))
.collect(toList());
return ArrayValue.newArrayValue().values(valuesNodes).build();
}
return valueToLiteralLegacy(value, itemType);
}
private static Value<?> handleNonNullLegacy(Object _value, GraphQLNonNull type) {
GraphQLType wrappedType = type.getWrappedType();
return valueToLiteralLegacy(_value, wrappedType);
}
private static Object serializeLegacy(GraphQLType type, Object value) {
if (type instanceof GraphQLScalarType) {
return ((GraphQLScalarType) type).getCoercing().serialize(value);
} else {
return ((GraphQLEnumType) type).serialize(value);
}
}
private static boolean isNullishLegacy(Object serialized) {
if (serialized instanceof Number) {
return Double.isNaN(((Number) serialized).doubleValue());
}
return serialized == null;
}
/**
* @return true if variable is absent from input, and if value is NOT a variable then false
*/
private static boolean isVariableAbsent(Value value, Map<String, NormalizedInputValue> variables) {
if (value instanceof VariableReference) {
VariableReference varRef = (VariableReference) value;
return !variables.containsKey(varRef.getName());
}
// Not variable, return false
return false;
}
}