Class: GraphQL::StaticValidation::VariablesAreUsedAndDefined

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

Instance Method Summary collapse

Methods included from Message::MessageHelper

#message

Instance Method Details

#validate(context) ⇒ Object


4
5
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/variables_are_used_and_defined.rb', line 4

def validate(context)
  # holds { name => used? } pairs
  declared_variables = {}

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

  context.visitor[GraphQL::Language::Nodes::VariableIdentifier] << -> (node, parent) {
    if declared_variables.key?(node.name)
      declared_variables[node.name] = true
    else
      context.errors << message("Variable $#{node.name} is used but not declared", node)
      GraphQL::Language::Visitor::SKIP
    end
  }

  context.visitor[GraphQL::Language::Nodes::OperationDefinition].leave << -> (node, parent) {
    unused_variables = declared_variables
      .select { |name, used| !used }
      .keys

    unused_variables.each do |var_name|
      context.errors << message("Variable $#{var_name} is declared but not used", node)
    end
  }
end