Class: GraphQL::StaticValidation::VariableUsagesAreAllowed

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

Instance Method Summary collapse

Methods included from Message::MessageHelper

#message

Instance Method Details

#validate(context) ⇒ Object


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

def validate(context)
  # holds { name => ast_node } pairs
  declared_variables = {}
  context.visitor[GraphQL::Language::Nodes::OperationDefinition] << ->(node, parent) {
    declared_variables = node.variables.each_with_object({}) { |var, memo| memo[var.name] = var }
  }

  context.visitor[GraphQL::Language::Nodes::Argument] << ->(node, parent) {
    node_values = if node.value.is_a?(Array)
      node.value
    else
      [node.value]
    end
    node_values = node_values.select { |value| value.is_a? GraphQL::Language::Nodes::VariableIdentifier }

    return if node_values.none?

    arguments = nil
    case parent
    when GraphQL::Language::Nodes::Field
      arguments = context.field_definition.arguments
    when GraphQL::Language::Nodes::Directive
      arguments = context.directive_definition.arguments
    when GraphQL::Language::Nodes::InputObject
      arg_type = context.argument_definition.type.unwrap
      if arg_type.is_a?(GraphQL::InputObjectType)
        arguments = arg_type.input_fields
      end
    else
      raise("Unexpected argument parent: #{parent}")
    end

    node_values.each do |node_value|
      var_defn_ast = declared_variables[node_value.name]
      # Might be undefined :(
      # VariablesAreUsedAndDefined can't finalize its search until the end of the document.
      var_defn_ast && arguments && validate_usage(arguments, node, var_defn_ast, context)
    end
  }
end