Class: GraphQL::Client
- Inherits:
-
Object
- Object
- GraphQL::Client
- 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
-
#initialize(endpoint:, token:, headers: {}) ⇒ Client
constructor
A new instance of Client.
-
#query(query, variables: {}) ⇒ Hash
The ‘data` portion of the GraphQL response.
Constructor Details
#initialize(endpoint:, token:, headers: {}) ⇒ Client
Returns a new instance of Client.
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.
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 |