Created
November 28, 2018 07:03
-
-
Save flavio-b/4ac96e5ec5cf799b03d8db232d1ebb0b to your computer and use it in GitHub Desktop.
A simple GraphQL wrapper around Faraday.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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