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


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

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) {
    return if !node.value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
    if parent.is_a?(GraphQL::Language::Nodes::Field)
      arguments = context.field_definition.arguments
    elsif parent.is_a?(GraphQL::Language::Nodes::Directive)
      arguments = context.directive_definition.arguments
    elsif parent.is_a?(GraphQL::Language::Nodes::InputObject)
      arguments = context.argument_definition.type.unwrap.input_fields
    else
      raise("Unexpected argument parent: #{parent}")
    end
    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 && validate_usage(arguments, node, var_defn_ast, context)
  }
end