module Crowdkit::API::RequestMethods

Public Instance Methods

agent() click to toggle source
# File lib/crowdkit/api/request_methods.rb, line 15
def agent
  raise Crowdkit::Unauthorized unless config.access_token
  @agent ||= Sawyer::Agent.new(config.api_endpoint, sawyer_options)
end

Private Instance Methods

boolean_from_response(method, path, options = {}) click to toggle source

Executes the request, checking if it was successful

@return [Boolean] True on success, false otherwise

# File lib/crowdkit/api/request_methods.rb, line 56
def boolean_from_response(method, path, options = {})
  response = request(method, path, options)
  response.status == 204
rescue Crowdkit::NotFound
  false
end
request(method, path, data, options = {}) click to toggle source
# File lib/crowdkit/api/request_methods.rb, line 22
def request(method, path, data, options = {})
  if data.is_a?(Hash)
    options[:headers] = data.delete(:headers) || {}
    options[:headers][:accept] = accept if accept = data.delete(:accept)
    options[:query]   = data.delete(:query) || {}
    if [:get, :head, :delete].include?(method)
      data.each do |key, _|
        options[:query][key] = data.delete(key)
      end
    else
      options[:headers]['Content-Type'] = 'application/json'
    end
  end

  begin
    Crowdkit.last_response = self.last_response = agent.call(method, URI::Parser.new.escape(path.to_s), data, options)
    @retried = false
    ResponseWrapper.new(self.last_response, self.client)
  rescue Crowdkit::ServiceError => e
    Crowdkit.last_response = self.last_response = Sawyer::Response.new(agent, e.response)

    # The per second limit was exceeded, let's try again in a second
    if e.response.status == 429 && !@retried
      sleep(1)
      @retried = true
      retry
    end
    raise e
  end
end
sawyer_options() click to toggle source
# File lib/crowdkit/api/request_methods.rb, line 63
def sawyer_options
  conn_opts = config.connection_options
  conn_opts[:builder] = config.stack
  { faraday: Faraday.new(conn_opts) }
end