Class: GraphQL::StaticValidation::LiteralValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/static_validation/literal_validator.rb

Overview

Test whether ast_value is a valid input for type

Instance Method Summary collapse

Constructor Details

#initialize(context:) ⇒ LiteralValidator

Returns a new instance of LiteralValidator



6
7
8
9
# File 'lib/graphql/static_validation/literal_validator.rb', line 6

def initialize(context:)
  @context = context
  @warden = context.warden
end

Instance Method Details

#validate(ast_value, type) ⇒ Object



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
# File 'lib/graphql/static_validation/literal_validator.rb', line 11

def validate(ast_value, type)
  if type.nil?
    # this means we're an undefined argument, see #present_input_field_values_are_valid
    return maybe_raise_if_invalid(ast_value) do
      false
    end
  elsif ast_value.is_a?(GraphQL::Language::Nodes::NullValue)
    maybe_raise_if_invalid(ast_value) do
      !type.kind.non_null?
    end
  elsif type.kind.non_null?
    maybe_raise_if_invalid(ast_value) do
      (!ast_value.nil?)
    end && validate(ast_value, type.of_type)
  elsif type.kind.list?
    item_type = type.of_type
    ensure_array(ast_value).all? { |val| validate(val, item_type) }
  elsif ast_value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
    true
  elsif type.kind.scalar? && constant_scalar?(ast_value)
    maybe_raise_if_invalid(ast_value) do
      type.valid_input?(ast_value, @context)
    end
  elsif type.kind.enum?
    maybe_raise_if_invalid(ast_value) do
      if ast_value.is_a?(GraphQL::Language::Nodes::Enum)
        type.valid_input?(ast_value.name, @context)
      else
        # if our ast_value isn't an Enum it's going to be invalid so return false
        false
      end
    end
  elsif type.kind.input_object? && ast_value.is_a?(GraphQL::Language::Nodes::InputObject)
    maybe_raise_if_invalid(ast_value) do
      required_input_fields_are_present(type, ast_value) && present_input_field_values_are_valid(type, ast_value)
    end
  else
    maybe_raise_if_invalid(ast_value) do
      false
    end
  end
end