Class: GraphQL::Query

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

Overview

Executes queries from strings against SCHEMA.

Examples:

query_str = "post(1) { title, comments { count } }"
query_ctx = {user: current_user}
query = GraphQL::Query.new(query_str, context: query_ctx)
result = query.as_result

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query_string, context: nil) ⇒ Query

Returns a new instance of Query.

Parameters:

  • query_string (String)

    the string to be parsed

  • context (Object) (defaults to: nil)

    an object which will be available to all nodes and fields in the schema



16
17
18
19
20
21
22
23
# File 'lib/graphql/query.rb', line 16

def initialize(query_string, context: nil)
  if !query_string.is_a?(String) || query_string.length == 0
    raise "You must send a query string, not a #{query_string.class.name}"
  end
  @query_string = query_string
  @root = parse(query_string)
  @context = context
end

Instance Attribute Details

#contextObject (readonly)

This is the object passed to #initialize as ‘context:`



11
12
13
# File 'lib/graphql/query.rb', line 11

def context
  @context
end

#query_stringObject (readonly)

Returns the value of attribute query_string.



12
13
14
# File 'lib/graphql/query.rb', line 12

def query_string
  @query_string
end

#rootObject (readonly)

Returns the value of attribute root.



12
13
14
# File 'lib/graphql/query.rb', line 12

def root
  @root
end

Instance Method Details

#as_resultHash

Calling #as_result more than once won’t cause the query to be re-run

Returns:

  • (Hash)

    result the JSON response to this query



27
28
29
# File 'lib/graphql/query.rb', line 27

def as_result
  @as_result ||= execute!
end

#get_variable(identifier) ⇒ Object

returns a query variable named ‘identifier`, otherwise raises.

Parameters:

  • identifier (String)


33
34
35
36
37
38
39
# File 'lib/graphql/query.rb', line 33

def get_variable(identifier)
  syntax_var = @root.variables.find { |v| v.identifier == identifier }
  if syntax_var.blank?
    raise "No variable found for #{identifier}, defined variables are #{@root.variables.map(&:identifier)}"
  end
  syntax_var
end