Skip to content

Instantly share code, notes, and snippets.

@flavio-b
Created November 28, 2018 07:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flavio-b/4ac96e5ec5cf799b03d8db232d1ebb0b to your computer and use it in GitHub Desktop.
Save flavio-b/4ac96e5ec5cf799b03d8db232d1ebb0b to your computer and use it in GitHub Desktop.
A simple GraphQL wrapper around Faraday.
require 'faraday'
require 'json'
class GraphQLClient
class << self
attr_accessor :base_site, :base_headers
def base_headers
@base_headers ||= {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
end
end
attr_accessor :site, :headers, :body, :response
def initialize(**args)
@site = args[:endpoint] || args[:site] || base_site
headers.merge!(args[:headers].to_h)
self
end
def query(**args)
self.body = {}
body["query"] = args[:query] || raise(ArgumentError 'Missing query string.')
body["variables"] = args[:variables]
body["operationName"] = args[:operation_name]
self.response = post
end
def headers
@headers ||= base_headers.to_h
end
private
def base_site
self.class.base_site
end
def base_headers
self.class.base_headers
end
def faraday_module
Faraday
end
def json_parser
JSON
end
def new_faraday_connection
faraday_module.new
end
def body_json
json_parser.generate(body)
end
def post
new_faraday_connection.post do |req|
req.url site
req.headers.merge! headers
req.body = body_json
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment