Class: GraphQL::Query::Variables

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/graphql/query/variables.rb

Overview

Read-only access to query variables, applying default values if needed.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, warden, ast_variables, provided_variables) ⇒ Variables

Returns a new instance of Variables.



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

def initialize(schema, warden, ast_variables, provided_variables)
  @schema = schema
  @warden = warden
  @provided_variables = provided_variables
  @errors = []
  @storage = ast_variables.each_with_object({}) do |ast_variable, memo|
    # Find the right value for this variable:
    # - First, use the value provided at runtime
    # - Then, fall back to the default value from the query string
    # If it's still nil, raise an error if it's required.
    variable_type = @schema.type_from_ast(ast_variable.type)
    variable_name = ast_variable.name
    default_value = ast_variable.default_value
    provided_value = @provided_variables[variable_name]
    value_was_provided = @provided_variables.key?(variable_name)

    validation_result = variable_type.validate_input(provided_value, @warden)
    if !validation_result.valid?
      # This finds variables that were required but not provided
      @errors << GraphQL::Query::VariableValidationError.new(ast_variable, variable_type, provided_value, validation_result)
    elsif value_was_provided
      # Add the variable if a value was provided
      memo[variable_name] = variable_type.coerce_input(provided_value)
    elsif default_value
      # Add the variable if it wasn't provided but it has a default value (including `null`)
      memo[variable_name] = GraphQL::Query::LiteralInput.coerce(variable_type, default_value, {})
    end
  end
end

Instance Attribute Details

#errorsArray<GraphQL::Query::VariableValidationError> (readonly)

Returns Any errors encountered when parsing the provided variables and literal values.

Returns:



9
10
11
# File 'lib/graphql/query/variables.rb', line 9

def errors
  @errors
end