Class: GQLi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/gqli/client.rb

Overview

GraphQL HTTP Client

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, params: {}, headers: {}, validate_query: true, options: {}) ⇒ Client

Returns a new instance of Client.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/gqli/client.rb', line 14

def initialize(url, params: {}, headers: {}, validate_query: true, options: {})
  @url = url
  @params = params
  @headers = headers
  @validate_query = validate_query
  @options = options
  @options[:read_timeout] ||= 60
  @options[:write_timeout] ||= 60
  @options[:connect_timeout] ||= 60

  @schema = Introspection.new(self) if validate_query
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



12
13
14
# File 'lib/gqli/client.rb', line 12

def headers
  @headers
end

#optionsObject (readonly)

Returns the value of attribute options.



12
13
14
# File 'lib/gqli/client.rb', line 12

def options
  @options
end

#paramsObject (readonly)

Returns the value of attribute params.



12
13
14
# File 'lib/gqli/client.rb', line 12

def params
  @params
end

#schemaObject (readonly)

Returns the value of attribute schema.



12
13
14
# File 'lib/gqli/client.rb', line 12

def schema
  @schema
end

#urlObject (readonly)

Returns the value of attribute url.



12
13
14
# File 'lib/gqli/client.rb', line 12

def url
  @url
end

#validate_queryObject (readonly)

Returns the value of attribute validate_query.



12
13
14
# File 'lib/gqli/client.rb', line 12

def validate_query
  @validate_query
end

Instance Method Details

#execute(query) ⇒ Object

Executes a query If validations are enabled, will perform validation check before request.



29
30
31
32
33
34
35
36
# File 'lib/gqli/client.rb', line 29

def execute(query)
  if validate_query
    validation = schema.validate(query)
    fail validation_error_message(validation) unless validation.valid?
  end

  execute!(query)
end

#execute!(query) ⇒ Object

Executres a query Ignores validations



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/gqli/client.rb', line 40

def execute!(query)
  http_response = request.post(@url, params: @params, json: { query: query.to_gql })

  fail "Error: #{http_response.reason}\nBody: #{http_response.body}" if http_response.status >= 300

  parsed_response = JSON.parse(http_response.to_s)
  data = parsed_response['data']
  errors = parsed_response['errors']

  Response.new(data, errors, query)
end

#valid?(query) ⇒ Boolean

Validates a query against the schema

Returns:

  • (Boolean)


53
54
55
56
57
# File 'lib/gqli/client.rb', line 53

def valid?(query)
  return true unless validate_query

  schema.valid?(query)
end