Class: GraphQL::Client

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

Overview

An HTTP wrapper that posts queries to a GraphQL endpoint and returns the ‘data` payload.

Instance Method Summary collapse

Constructor Details

#initialize(endpoint:, token:, headers: {}) ⇒ Client

Returns a new instance of Client.

Parameters:

  • endpoint (String)

    the GraphQL endpoint URL.

  • token (String)

    the bearer access token used to authorize the request.

  • headers (Hash) (defaults to: {})

    any extra headers required by the API (e.g. a version pin).



11
12
13
14
15
# File 'lib/graphql/client.rb', line 11

def initialize(endpoint:, token:, headers: {})
  @endpoint = URI endpoint
  @token = token
  @headers = headers
end

Instance Method Details

#query(query, variables: {}) ⇒ Hash

Returns the ‘data` portion of the GraphQL response.

Parameters:

  • query (String)

    the GraphQL query string.

  • variables (Hash) (defaults to: {})

    the variables to interpolate into the query.

Returns:

  • (Hash)

    the ‘data` portion of the GraphQL response.

Raises:



20
21
22
23
24
25
26
27
# File 'lib/graphql/client.rb', line 20

def query(query, variables: {})
  response = Net::HTTP.post @endpoint, { query:, variables: }.to_json, request_headers
  raise Unauthorized, response.body if response.code == '401'
  raise Error, response.body unless response.is_a? Net::HTTPSuccess
  body = JSON.parse(response.body)
  raise Error, body['errors'].pluck('message').join('; ') if body['errors'].present?
  body.fetch('data')
end