Class: Rails::GraphQL::ToGQL

Inherits:
Arel::Visitors::Visitor
  • Object
show all
Defined in:
lib/rails/graphql/to_gql.rb

Overview

GraphQL ToGQL

This class can turn any class related to GraphQL into its GraphQL string representation. It was developed more for testing purposes, but it can also used by describing purposes or generating API description pages.

Constant Summary collapse

DESCRIBE_TYPES =
%i[scalar enum input_object interface union object].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.compile(node, **xargs) ⇒ Object

Trigger a new compile process



17
18
19
# File 'lib/rails/graphql/to_gql.rb', line 17

def self.compile(node, **xargs)
  new.compile(node, **xargs)
end

.describe(schema, **xargs) ⇒ Object

Trigger a new describe process



22
23
24
# File 'lib/rails/graphql/to_gql.rb', line 22

def self.describe(schema, **xargs)
  new.describe(schema, **xargs)
end

Instance Method Details

#compile(node, collector = nil, with_descriptions: true) ⇒ Object

Describe the given node as GraphQL



27
28
29
30
31
# File 'lib/rails/graphql/to_gql.rb', line 27

def compile(node, collector = nil, with_descriptions: true)
  collector ||= Collectors::IdentedCollector.new
  @with_descriptions = with_descriptions
  accept(node, collector).value
end

#describe(schema, collector = nil, with_descriptions: true, with_spec: nil) ⇒ Object

Describe the given schema as GraphQL, with all types and directives



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rails/graphql/to_gql.rb', line 34

def describe(schema, collector = nil, with_descriptions: true, with_spec: nil)
  collector ||= Collectors::IdentedCollector.new
  @with_descriptions = with_descriptions
  @with_spec = with_spec.nil? ? schema.introspection? : with_spec
  @namespace = schema.namespace

  GraphQL.type_map.each_from(@namespace, base_class: :Type)
    .group_by(&:kind).values_at(*DESCRIBE_TYPES)
    .prepend([schema]).each do |items|
      items&.sort_by(&:gql_name)&.each do |item|
        next if !@with_spec && item.try(:internal?)

        next visit_Rails_GraphQL_Type_Object(item, collector).eol \
          if item.is_a?(::OpenStruct) && item.object?

        accept(item, collector).eol
      end
    end

  GraphQL.type_map.each_from(schema.namespace, base_class: :Directive)
    .sort_by(&:gql_name).each do |item|
      next if !@with_spec && item.spec_object
      accept(item, collector).eol
    end

  collector.value.chomp
end