|
| 1 | +package graphql.schema.validation; |
| 2 | + |
| 3 | +import graphql.execution.NonNullableValueCoercedAsNullException; |
| 4 | +import graphql.execution.ValuesResolver; |
| 5 | +import graphql.language.Value; |
| 6 | +import graphql.schema.CoercingParseValueException; |
| 7 | +import graphql.schema.GraphQLArgument; |
| 8 | +import graphql.schema.GraphQLInputType; |
| 9 | +import graphql.schema.GraphQLSchema; |
| 10 | +import graphql.schema.GraphQLSchemaElement; |
| 11 | +import graphql.schema.GraphQLTypeVisitorStub; |
| 12 | +import graphql.schema.ValueState; |
| 13 | +import graphql.util.TraversalControl; |
| 14 | +import graphql.util.TraverserContext; |
| 15 | +import graphql.validation.ValidationUtil; |
| 16 | + |
| 17 | +import static graphql.schema.GraphQLTypeUtil.simplePrint; |
| 18 | +import static java.lang.String.format; |
| 19 | + |
| 20 | +public class AppliedDirectiveArgumentsAreValid extends GraphQLTypeVisitorStub { |
| 21 | + |
| 22 | + private ValidationUtil validationUtil = new ValidationUtil(); |
| 23 | + |
| 24 | + |
| 25 | + public TraversalControl visitGraphQLArgument(GraphQLArgument argument, TraverserContext<GraphQLSchemaElement> context) { |
| 26 | + // a directive argument is represented as GraphQLArgument.value |
| 27 | + if (!argument.hasSetValue()) { |
| 28 | + return TraversalControl.CONTINUE; |
| 29 | + } |
| 30 | + GraphQLSchema schema = context.getVarFromParents(GraphQLSchema.class); |
| 31 | + SchemaValidationErrorCollector errorCollector = context.getVarFromParents(SchemaValidationErrorCollector.class); |
| 32 | + ValueState argumentState = argument.getValueState(); |
| 33 | + boolean invalid = false; |
| 34 | + if (argumentState == ValueState.LITERAL && |
| 35 | + !validationUtil.isValidLiteralValue((Value<?>) argument.getArgumentValue(), argument.getType(), schema)) { |
| 36 | + invalid = true; |
| 37 | + } else if (argumentState == ValueState.EXTERNAL_VALUE && |
| 38 | + !isValidExternalValue(schema, argument.getArgumentValue(), argument.getType())) { |
| 39 | + invalid = true; |
| 40 | + } |
| 41 | + if (invalid) { |
| 42 | + String message = format("Invalid argument %s for type %s for applied directive", argument.getValueState(), simplePrint(argument.getType())); |
| 43 | + errorCollector.addError(new SchemaValidationError(SchemaValidationErrorType.InvalidAppliedDirectiveArgument, message)); |
| 44 | + } |
| 45 | + return TraversalControl.CONTINUE; |
| 46 | + } |
| 47 | + |
| 48 | + private boolean isValidExternalValue(GraphQLSchema schema, Object externalValue, GraphQLInputType type) { |
| 49 | + try { |
| 50 | + ValuesResolver.externalValueToInternalValue(schema.getCodeRegistry().getFieldVisibility(), externalValue, type); |
| 51 | + return true; |
| 52 | + } catch (CoercingParseValueException | NonNullableValueCoercedAsNullException e) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments