Skip to content

Instantly share code, notes, and snippets.

@brand-it
Last active March 24, 2022 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brand-it/5d9ff00800b86349a645dc01cdbb2206 to your computer and use it in GitHub Desktop.
Save brand-it/5d9ff00800b86349a645dc01cdbb2206 to your computer and use it in GitHub Desktop.
Simple tool for making GQL request with vanilla ruby
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