Class: GraphQL::Client

Inherits:
Object
  • Object
show all
Extended by:
CollocatedEnforcement
Defined in:
lib/graphql/client.rb,
lib/graphql/client/http.rb,
lib/graphql/client/list.rb,
lib/graphql/client/error.rb,
lib/graphql/client/errors.rb,
lib/graphql/client/erubis.rb,
lib/graphql/client/railtie.rb,
lib/graphql/client/response.rb,
lib/graphql/client/definition.rb,
lib/graphql/client/view_module.rb,
lib/graphql/client/query_result.rb,
lib/graphql/client/document_types.rb,
lib/graphql/client/erubi_enhancer.rb,
lib/graphql/client/log_subscriber.rb,
lib/graphql/client/query_typename.rb,
lib/graphql/client/erubis_enhancer.rb,
lib/graphql/client/fragment_definition.rb,
lib/graphql/client/definition_variables.rb,
lib/graphql/client/operation_definition.rb,
lib/graphql/client/collocated_enforcement.rb,
lib/graphql/client/hash_with_indifferent_access.rb

Overview

GraphQL Client helps build and execute queries against a GraphQL backend.

A client instance SHOULD be configured with a schema to enable query validation. And SHOULD also be configured with a backend “execute” adapter to point at a remote GraphQL HTTP service or execute directly against a Schema object.

Defined Under Namespace

Modules: CollocatedEnforcement, DefinitionVariables, DocumentTypes, ErubiEnhancer, ErubisEnhancer, LazyName, QueryTypename, ViewModule Classes: Definition, DynamicQueryError, Error, Errors, Erubis, FragmentDefinition, HTTP, HashWithIndifferentAccess, List, LogSubscriber, NonCollocatedCallerError, NotImplementedError, OperationDefinition, QueryResult, Railtie, Response, ValidationError

Constant Summary collapse

IntrospectionDocument =
GraphQL.parse(GraphQL::Introspection::INTROSPECTION_QUERY).deep_freeze
WHITELISTED_GEM_NAMES =

Collcation will not be enforced if a stack trace includes any of these gems.

%w{pry byebug}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CollocatedEnforcement

allow_noncollocated_callers

Constructor Details

#initialize(schema:, execute: nil, enforce_collocated_callers: false) ⇒ Client

Returns a new instance of Client.



85
86
87
88
89
90
91
92
# File 'lib/graphql/client.rb', line 85

def initialize(schema:, execute: nil, enforce_collocated_callers: false)
  @schema = self.class.load_schema(schema)
  @execute = execute
  @document = GraphQL::Language::Nodes::Document.new(definitions: [])
  @document_tracking_enabled = false
  @allow_dynamic_queries = false
  @enforce_collocated_callers = enforce_collocated_callers
end

Instance Attribute Details

#allow_dynamic_queriesObject

Deprecated: Allow dynamically generated queries to be passed to Client#query.

This ability will eventually be removed in future versions.



43
44
45
# File 'lib/graphql/client.rb', line 43

def allow_dynamic_queries
  @allow_dynamic_queries
end

#documentObject (readonly)

Returns the value of attribute document.



275
276
277
# File 'lib/graphql/client.rb', line 275

def document
  @document
end

#document_tracking_enabledObject

Returns the value of attribute document_tracking_enabled.



34
35
36
# File 'lib/graphql/client.rb', line 34

def document_tracking_enabled
  @document_tracking_enabled
end

#enforce_collocated_callersObject (readonly)

Public: Check if collocated caller enforcement is enabled.



37
38
39
# File 'lib/graphql/client.rb', line 37

def enforce_collocated_callers
  @enforce_collocated_callers
end

#executeObject (readonly)

Returns the value of attribute execute.



32
33
34
# File 'lib/graphql/client.rb', line 32

def execute
  @execute
end

#schemaObject (readonly)

Returns the value of attribute schema.



32
33
34
# File 'lib/graphql/client.rb', line 32

def schema
  @schema
end

Class Method Details

.dump_schema(schema, io = nil) ⇒ Object



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 64

def self.dump_schema(schema, io = nil)
  unless schema.respond_to?(:execute)
    raise TypeError, "expected schema to respond to #execute(), but was #{schema.class}"
  end

  result = schema.execute(
    document: IntrospectionDocument,
    operation_name: "IntrospectionQuery",
    variables: {},
    context: {}
  )

  if io
    io = File.open(io, "w") if io.is_a?(String)
    io.write(JSON.pretty_generate(result))
    io.close_write
  end

  result
end

.load_schema(schema) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/graphql/client.rb', line 45

def self.load_schema(schema)
  case schema
  when GraphQL::Schema
    schema
  when Hash
    GraphQL::Schema::Loader.load(schema)
  when String
    if schema.end_with?(".json") && File.exist?(schema)
      load_schema(File.read(schema))
    elsif schema =~ /\A\s*{/
      load_schema(JSON.parse(schema))
    end
  else
    load_schema(dump_schema(schema)) if schema.respond_to?(:execute)
  end
end

Instance Method Details

#create_operation(fragment, filename = nil, lineno = nil) ⇒ Object

Public: Create operation definition from a fragment definition.

Automatically determines operation variable set.

Examples

FooFragment = Client.parse <<-'GRAPHQL'
  fragment on Mutation {
    updateFoo(id: $id, content: $content)
  }
GRAPHQL

# mutation($id: ID!, $content: String!) {
#   updateFoo(id: $id, content: $content)
# }
FooMutation = Client.create_operation(FooFragment)

fragment - A FragmentDefinition definition.

Returns an OperationDefinition.



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/graphql/client.rb', line 238

def create_operation(fragment, filename = nil, lineno = nil)
  unless fragment.is_a?(GraphQL::Client::FragmentDefinition)
    raise TypeError, "expected fragment to be a GraphQL::Client::FragmentDefinition, but was #{fragment.class}"
  end

  if filename.nil? && lineno.nil?
    location = caller_locations(1, 1).first
    filename = location.path
    lineno = location.lineno
  end

  variables = GraphQL::Client::DefinitionVariables.operation_variables(self.schema, fragment.document, fragment.definition_name)
  type_name = fragment.definition_node.type.name

  if schema.query && type_name == schema.query.name
    operation_type = "query"
  elsif schema.mutation && type_name == schema.mutation.name
    operation_type = "mutation"
  elsif schema.subscription && type_name == schema.subscription.name
    operation_type = "subscription"
  else
    types = [schema.query, schema.mutation, schema.subscription].compact
    raise Error, "Fragment must be defined on #{types.map(&:name).join(", ")}"
  end

  doc_ast = GraphQL::Language::Nodes::Document.new(definitions: [
    GraphQL::Language::Nodes::OperationDefinition.new(
      operation_type: operation_type,
      variables: variables,
      selections: [
        GraphQL::Language::Nodes::FragmentSpread.new(name: fragment.name)
      ]
    )
  ])
  parse(doc_ast.to_query_string, filename, lineno)
end

#parse(str, filename = nil, lineno = nil) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/graphql/client.rb', line 94

def parse(str, filename = nil, lineno = nil)
  if filename.nil? && lineno.nil?
    location = caller_locations(1, 1).first
    filename = location.path
    lineno = location.lineno
  end

  unless filename.is_a?(String)
    raise TypeError, "expected filename to be a String, but was #{filename.class}"
  end

  unless lineno.is_a?(Integer)
    raise TypeError, "expected lineno to be a Integer, but was #{lineno.class}"
  end

  source_location = [filename, lineno].freeze

  definition_dependencies = Set.new

  str = str.gsub(/\.\.\.([a-zA-Z0-9_]+(::[a-zA-Z0-9_]+)*)/) do
    match = Regexp.last_match
    const_name = match[1]

    if str.match(/fragment\s*#{const_name}/)
      match[0]
    else
      begin
        fragment = ActiveSupport::Inflector.constantize(const_name)
      rescue NameError
        fragment = nil
      end

      case fragment
      when FragmentDefinition
        definition_dependencies.merge(fragment.document.definitions)
        "...#{fragment.definition_name}"
      else
        if fragment
          message = "expected #{const_name} to be a #{FragmentDefinition}, but was a #{fragment.class}."
          if fragment.is_a?(Module) && fragment.constants.any?
            message += " Did you mean #{fragment}::#{fragment.constants.first}?"
          end
        else
          message = "uninitialized constant #{const_name}"
        end

        error = ValidationError.new(message)
        error.set_backtrace(["#{filename}:#{lineno + match.pre_match.count("\n") + 1}"] + caller)
        raise error
      end
    end
  end

  doc = GraphQL.parse(str)

  doc.definitions.each do |node|
    node.name ||= "__anonymous__"
  end

  document_dependencies = Language::Nodes::Document.new(definitions: doc.definitions + definition_dependencies.to_a)

  rules = GraphQL::StaticValidation::ALL_RULES - [
    GraphQL::StaticValidation::FragmentsAreUsed,
    GraphQL::StaticValidation::FieldsHaveAppropriateSelections
  ]
  validator = GraphQL::StaticValidation::Validator.new(schema: self.schema, rules: rules)
  query = GraphQL::Query.new(self.schema, document: document_dependencies)

  errors = validator.validate(query)
  errors.fetch(:errors).each do |error|
    error_hash = error.to_h
    validation_line = error_hash["locations"][0]["line"]
    error = ValidationError.new(error_hash["message"])
    error.set_backtrace(["#{filename}:#{lineno + validation_line}"] + caller)
    raise error
  end

  document_types = DocumentTypes.analyze_types(self.schema, doc).freeze

  QueryTypename.insert_typename_fields(doc, types: document_types)

  definitions = {}
  doc.definitions.each do |node|
    node.name = nil if node.name == "__anonymous__"
    sliced_document = Language::DefinitionSlice.slice(document_dependencies, node.name)
    definition = Definition.for(
      schema: self.schema,
      node: node,
      document: sliced_document,
      document_types: document_types,
      source_location: source_location,
      enforce_collocated_callers: enforce_collocated_callers
    )
    definitions[node.name] = definition
  end

  rename_node = ->(node, _parent) do
    definition = definitions[node.name]
    if definition
      node.extend(LazyName)
      node.name = -> { definition.definition_name }
    end
  end
  visitor = Language::Visitor.new(doc)
  visitor[Language::Nodes::FragmentDefinition].leave << rename_node
  visitor[Language::Nodes::OperationDefinition].leave << rename_node
  visitor[Language::Nodes::FragmentSpread].leave << rename_node
  visitor.visit

  doc.deep_freeze

  document.definitions.concat(doc.definitions) if document_tracking_enabled

  if definitions[nil]
    definitions[nil]
  else
    Module.new do
      definitions.each do |name, definition|
        const_set(name, definition)
      end
    end
  end
end

#query(definition, variables: {}, context: {}) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/graphql/client.rb', line 277

def query(definition, variables: {}, context: {})
  raise NotImplementedError, "client network execution not configured" unless execute

  unless definition.is_a?(OperationDefinition)
    raise TypeError, "expected definition to be a #{OperationDefinition.name} but was #{document.class.name}"
  end

  if allow_dynamic_queries == false && definition.name.nil?
    raise DynamicQueryError, "expected definition to be assigned to a static constant https://git.io/vXXSE"
  end

  variables = deep_stringify_keys(variables)

  document = definition.document
  operation = definition.definition_node

  payload = {
    document: document,
    operation_name: operation.name,
    operation_type: operation.operation_type,
    variables: variables,
    context: context
  }

  result = ActiveSupport::Notifications.instrument("query.graphql", payload) do
    execute.execute(
      document: document,
      operation_name: operation.name,
      variables: variables,
      context: context
    )
  end

  data, errors, extensions = result.values_at("data", "errors", "extensions")

  errors ||= []
  GraphQL::Client::Errors.normalize_error_paths(data, errors)

  errors.each do |error|
    error_payload = payload.merge(message: error["message"], error: error)
    ActiveSupport::Notifications.instrument("error.graphql", error_payload)
  end

  Response.new(
    data: definition.new(data, Errors.new(errors, ["data"])),
    errors: Errors.new(errors),
    extensions: extensions
  )
end