Class: GraphQL::Client::QueryTypename::InsertTypenameVisitor

Inherits:
Language::Visitor
  • Object
show all
Defined in:
lib/graphql/client/query_typename.rb

Overview

GraphQL 1.9 introduces a new visitor class and doesn’t expose writer methods for node attributes. So, use the node mutation API instead.

Instance Method Summary collapse

Constructor Details

#initialize(document, types:) ⇒ InsertTypenameVisitor

Returns a new instance of InsertTypenameVisitor.



22
23
24
25
# File 'lib/graphql/client/query_typename.rb', line 22

def initialize(document, types:)
  @types = types
  super(document)
end

Instance Method Details

#add_typename(node, parent) ⇒ Object



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

def add_typename(node, parent)
  type = @types[node]
  type = type && type.unwrap

  if (node.selections.any? && (type.nil? || type.kind.interface? || type.kind.union?)) ||
    (node.selections.none? && (type && type.kind.object?))
    names = QueryTypename.node_flatten_selections(node.selections).map { |s| s.respond_to?(:name) ? s.name : nil }
    names = Set.new(names.compact)

    if names.include?("__typename")
      yield(node, parent)
    else
      node_with_typename = node.merge(selections: [GraphQL::Language::Nodes::Field.new(name: "__typename")] + node.selections)
      yield(node_with_typename, parent)
    end
  else
    yield(node, parent)
  end
end

#on_field(node, parent) ⇒ Object



51
52
53
# File 'lib/graphql/client/query_typename.rb', line 51

def on_field(node, parent)
  add_typename(node, parent) { |n, p| super(n, p) }
end

#on_fragment_definition(node, parent) ⇒ Object



55
56
57
# File 'lib/graphql/client/query_typename.rb', line 55

def on_fragment_definition(node, parent)
  add_typename(node, parent) { |n, p| super(n, p) }
end

#on_operation_definition(node, parent) ⇒ Object



47
48
49
# File 'lib/graphql/client/query_typename.rb', line 47

def on_operation_definition(node, parent)
  add_typename(node, parent) { |n, p| super(n, p) }
end