Class: GraphQL::StaticValidation::VariableDefaultValuesAreCorrectlyTyped

Inherits:
Object
  • Object
show all
Includes:
Message::MessageHelper
Defined in:
lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb

Instance Method Summary collapse

Methods included from Message::MessageHelper

#message

Instance Method Details

#validate(context) ⇒ Object


6
7
8
9
10
11
12
13
# File 'lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb', line 6

def validate(context)
  literal_validator = GraphQL::StaticValidation::LiteralValidator.new
  context.visitor[GraphQL::Language::Nodes::VariableDefinition] << ->(node, parent) {
    if !node.default_value.nil?
      validate_default_value(node, literal_validator, context)
    end
  }
end

#validate_default_value(node, literal_validator, context) ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
# File 'lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb', line 15

def validate_default_value(node, literal_validator, context)
  value = node.default_value
  if node.type.is_a?(GraphQL::Language::Nodes::NonNullType)
    context.errors << message("Non-null variable $#{node.name} can't have a default value", node, context: context)
  else
    type = context.schema.type_from_ast(node.type)
    if !literal_validator.validate(value, type)
      context.errors << message("Default value for $#{node.name} doesn't match type #{type}", node, context: context)
    end
  end
end