Class: GraphQL::Stitching::Document

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

Constant Summary collapse

SUPPORTED_OPERATIONS =
["query", "mutation"].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string_or_ast, operation_name: nil) ⇒ Document

Returns a new instance of Document.



10
11
12
13
14
15
16
17
18
# File 'lib/graphql/stitching/document.rb', line 10

def initialize(string_or_ast, operation_name: nil)
  @ast = if string_or_ast.is_a?(String)
    GraphQL.parse(string_or_ast)
  else
    string_or_ast
  end

  @operation_name = operation_name
end

Instance Attribute Details

#astObject (readonly)

Returns the value of attribute ast.



8
9
10
# File 'lib/graphql/stitching/document.rb', line 8

def ast
  @ast
end

#operation_nameObject (readonly)

Returns the value of attribute operation_name.



8
9
10
# File 'lib/graphql/stitching/document.rb', line 8

def operation_name
  @operation_name
end

Instance Method Details

#digestObject



24
25
26
# File 'lib/graphql/stitching/document.rb', line 24

def digest
  @digest ||= Digest::SHA2.hexdigest(string)
end

#fragment_definitionsObject



52
53
54
55
56
# File 'lib/graphql/stitching/document.rb', line 52

def fragment_definitions
  @fragment_definitions ||= @ast.definitions.each_with_object({}) do |d, memo|
    memo[d.name] = d if d.is_a?(GraphQL::Language::Nodes::FragmentDefinition)
  end
end

#operationObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/graphql/stitching/document.rb', line 28

def operation
  @operation ||= begin
    operation_defs = @ast.definitions.select do |d|
      next unless d.is_a?(GraphQL::Language::Nodes::OperationDefinition)
      next unless SUPPORTED_OPERATIONS.include?(d.operation_type)
      @operation_name ? d.name == @operation_name : true
    end

    if operation_defs.length < 1
      raise GraphQL::ExecutionError, "Invalid root operation."
    elsif operation_defs.length > 1
      raise GraphQL::ExecutionError, "An operation name is required when sending multiple operations."
    end

    operation_defs.first
  end
end

#stringObject



20
21
22
# File 'lib/graphql/stitching/document.rb', line 20

def string
  @string ||= GraphQL::Language::Printer.new.print(@ast)
end

#variable_definitionsObject



46
47
48
49
50
# File 'lib/graphql/stitching/document.rb', line 46

def variable_definitions
  @variable_definitions ||= operation.variables.each_with_object({}) do |v, memo|
    memo[v.name] = v.type
  end
end