Class: GraphQL::Client::Query::Document

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

Constant Summary collapse

DEFAULT_OPERATION_NAME =
'default'
DUPLICATE_OPERATION_NAME =
Class.new(StandardError)
INVALID_DOCUMENT =
Class.new(StandardError)
INVALID_FRAGMENT_TARGET =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema) {|_self| ... } ⇒ Document

Returns a new instance of Document.

Yields:

  • (_self)

Yield Parameters:



15
16
17
18
19
20
21
# File 'lib/graphql_client/query/document.rb', line 15

def initialize(schema)
  @schema = schema
  @fragments = {}
  @operations = {}

  yield self if block_given?
end

Instance Attribute Details

#fragmentsObject (readonly)

Returns the value of attribute fragments.



13
14
15
# File 'lib/graphql_client/query/document.rb', line 13

def fragments
  @fragments
end

#operationsObject (readonly)

Returns the value of attribute operations.



13
14
15
# File 'lib/graphql_client/query/document.rb', line 13

def operations
  @operations
end

#schemaObject (readonly)

Returns the value of attribute schema.



13
14
15
# File 'lib/graphql_client/query/document.rb', line 13

def schema
  @schema
end

Instance Method Details

#add_mutation(name = nil, &block) ⇒ Object



23
24
25
# File 'lib/graphql_client/query/document.rb', line 23

def add_mutation(name = nil, &block)
  add_operation(MutationOperation, name, &block)
end

#add_query(name = nil, &block) ⇒ Object



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

def add_query(name = nil, &block)
  add_operation(QueryOperation, name, &block)
end

#define_fragment(name, on:) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/graphql_client/query/document.rb', line 31

def define_fragment(name, on:)
  type = schema.type(on)

  unless type.object? || type.interface? || type.union?
    raise INVALID_FRAGMENT_TARGET, "invalid target type (#{type.kind}) for fragment #{name}"
  end

  fragment = Fragment.new(name, type, document: self)
  @fragments[name] = fragment

  if block_given?
    yield fragment
  else
    fragment
  end
end

#fragment_definitionsObject



48
49
50
# File 'lib/graphql_client/query/document.rb', line 48

def fragment_definitions
  fragments.values.map(&:to_definition).join("\n")
end

#to_queryObject Also known as: to_s



52
53
54
55
56
57
# File 'lib/graphql_client/query/document.rb', line 52

def to_query
  ''.dup.tap do |query_string|
    query_string << "#{fragment_definitions}\n" unless fragments.empty?
    query_string << operations.values.map(&:to_query).join("\n")
  end
end