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) ⇒ Client

Returns a new instance of Client.



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

def initialize(url, params: {}, headers: {}, validate_query: true)
  @url = url
  @params = params
  @headers = headers
  @validate_query = validate_query

  @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

#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.



25
26
27
28
29
30
31
32
# File 'lib/gqli/client.rb', line 25

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



36
37
38
39
40
41
42
43
44
# File 'lib/gqli/client.rb', line 36

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

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

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

  Response.new(data, query)
end

#valid?(query) ⇒ Boolean

Validates a query against the schema

Returns:

  • (Boolean)


47
48
49
50
51
# File 'lib/gqli/client.rb', line 47

def valid?(query)
  return true unless validate_query

  schema.valid?(query)
end