Last active
March 24, 2022 21:36
-
-
Save brand-it/5d9ff00800b86349a645dc01cdbb2206 to your computer and use it in GitHub Desktop.
Simple tool for making GQL request with vanilla ruby
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 'uri' | |
require 'json' | |
require 'net/http' | |
class Gql | |
class Base | |
Response = Struct.new(:http) do | |
def success? | |
http.is_a?(Net::HTTPSuccess) | |
end | |
def body | |
@body ||= http.read_body | |
end | |
def parsed_body | |
return {} if body.nil? | |
@parsed_body ||= JSON.parse(body) | |
rescue JSON::ParserError | |
nil | |
end | |
end | |
attr_reader :endpoint, :token, :request_accept | |
def initialize(endpoint, token, request_accept = nil) | |
@endpoint = endpoint | |
@token = token | |
@request_accept = request_accept | |
end | |
def request(body) | |
uri = URI(endpoint) | |
https = https(uri) | |
request = Net::HTTP::Post.new(uri) | |
request['Authorization'] = "Bearer #{token}" | |
request['Content-Type'] = 'application/json' | |
request['Accept'] = request_accept if request_accept | |
request.body = body.to_json if body | |
Response.new(https.request(request) | |
end | |
def https(uri) | |
Net::HTTP.new(uri.host, uri.port).tap do |http| | |
http.use_ssl = true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment