Class: GraphQL::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/client.rb,
lib/graphql/client/const_proxy.rb,
lib/graphql/client/query_result.rb

Defined Under Namespace

Modules: ConstProxy Classes: Definition, Error, QueryResult, ValidationError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema:) ⇒ Client

Returns a new instance of Client.



17
18
19
20
# File 'lib/graphql/client.rb', line 17

def initialize(schema:)
  @schema = schema
  @definitions = []
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



15
16
17
# File 'lib/graphql/client.rb', line 15

def schema
  @schema
end

Instance Method Details

#_parse(name, str) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/graphql/client.rb', line 55

def _parse(name, str)
  str = str.strip

  str = str.gsub(/\.\.\.([a-zA-Z0-9_]+(::[a-zA-Z0-9_]+)+)(\.([a-zA-Z0-9_]+))?/) { |m|
    const_name, fragment_name = $1, $4
    nodes = ActiveSupport::Inflector.constantize(const_name)._nodes

    fragment_name = fragment_name ?
      nodes.find { |n| n.name.end_with?(fragment_name) }.name : # XXX
      nodes.first.name

    "...#{fragment_name}"
  }

  doc = GraphQL::Relay::Parser.parse(str)

  mutator = GraphQL::Language::Mutator.new(doc)

  aliases = {}
  doc.definitions.each do |definition|
    aliases[definition.name] = (name.split("::") << definition.name).compact.join("__")
  end
  mutator.rename_definitions(aliases)

  # TODO: Make this __typename injection optional
  mutator.prepend_selection(GraphQL::Language::Nodes::Field.new(name: "__typename").deep_freeze)

  doc.definitions.map(&:deep_freeze)
end

#documentObject



85
86
87
# File 'lib/graphql/client.rb', line 85

def document
  GraphQL::Language::Nodes::Document.new(definitions: @definitions.flat_map(&:_nodes)).deep_freeze
end

#parse(str) ⇒ Object



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

def parse(str)
  definition = ConstProxy.new { |name| Definition.new(client: self, name: name, source: str) }
  @definitions << definition
  definition
end

#validate!Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/graphql/client.rb', line 89

def validate!
  validator = StaticValidation::Validator.new(schema: @schema)
  query = Query.new(@schema, document: document)

  validator.validate(query).fetch(:errors).each do |error|
    raise ValidationError, error["message"]
  end

  nil
end