class GoFlippy::HttpClient

Constants

HTTP_API_KEY_HEADER

Public Class Methods

new(api_key, opts = {}) click to toggle source
# File lib/goflippy-ruby/http_client.rb, line 10
def initialize(api_key, opts = {})
  @api_key = api_key
  @api_uri = opts.api_uri
  @open_timeout = opts.open_timeout
  @read_timeout = opts.read_timeout
end

Public Instance Methods

get(path, params = {}) click to toggle source
# File lib/goflippy-ruby/http_client.rb, line 17
def get(path, params = {})
  uri = uri(path, params)

  req = Net::HTTP::Get.new(uri.request_uri)
  req['Accept'] = 'application/json'
  req[HTTP_API_KEY_HEADER] = 'application/json'
  request(uri, req)
end
post(path, params = {}) click to toggle source
# File lib/goflippy-ruby/http_client.rb, line 26
def post(path, params = {})
  uri = uri(path, params)

  req = Net::HTTP::Post.new(uri.request_uri)
  req['Accept'] = 'application/json'
  req['Content-Type'] = 'application/json'
  req[HTTP_API_KEY_HEADER] = 'application/json'
  req.body = params.to_json unless params.empty?
  request(uri, req)
end

Private Instance Methods

request(uri, req) click to toggle source
# File lib/goflippy-ruby/http_client.rb, line 48
def request(uri, req)
  begin
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.open_timeout = @open_timeout
      http.read_timeout = @read_timeout
      http.request(req)
    end
    case response
      when Net::HTTPSuccess
        json = response.body
        return JSON.parse(json, symbolize_names: true)
      when Net::HTTPRedirection
        request(URI.parse(response['location']), req)
      else
        Logger.error(response.value)
    end
  rescue => e
    Logger.error(e)
  end
  response
end
uri(path, params = {}) click to toggle source
# File lib/goflippy-ruby/http_client.rb, line 39
def uri(path, params = {})
  if params.empty?
    URI.parse("#{@api_uri}#{path}")
  else
    encoded_params = URI.encode_www_form(params)
    URI.parse("#{@api_uri}#{path}/?#{encoded_params}")
  end
end