module TriviaCrack::API::Common

Constants

API_HOST

Internal: The host name of the Trivia Crack API.

Public Instance Methods

get(url, parameters: nil) click to toggle source

Internal: Makes a GET request to the Trivia Crack API using the set of default headers.

url - The URL of the TriviaCrack API resource. parameters - The parameters to send with the request.

Returns a Unirest Response object with the server's response. Raises TriviaCrack:Errors::RequestError if the request fails.

# File lib/triviacrack/api/common.rb, line 18
def get(url, parameters: nil)
  response = Unirest.get "#{API_HOST}#{url}", parameters: parameters,
                                              headers: default_headers

  check_response url, response
end
post(url, parameters: nil) click to toggle source

Internal: Makes a POST request to the Trivia Crack API using the set of default headers.

url - The URL of the TriviaCrack API resource. parameters - The parameters to send with the request.

Returns a Unirest Response object with the server's response. Raises TriviaCrack:Errors::RequestError if the request fails.

# File lib/triviacrack/api/common.rb, line 33
def post(url, parameters: nil)
  response = Unirest.post "#{API_HOST}#{url}", parameters: parameters,
                                               headers: default_headers

  check_response url, response
end

Private Instance Methods

check_response(url, response) click to toggle source

Internal: Checks the response's code to see if the request was successful

response - Unirest response returned by the API.

Returns the response object. Raises TriviaCrack:Errors::RequestError if the request failed.

# File lib/triviacrack/api/common.rb, line 66
def check_response(url, response)
  if not response.code.between? 200, 299
    raise TriviaCrack::Errors::RequestError.new(response.code, url, response.body),
      "Request to #{API_HOST}#{url} failed with code #{response.code}."
  end

  response
end
default_headers() click to toggle source

Internal: Constructs the set of headers needed to make requests to the Trivia Crack API.

Returns a hash of headers.

# File lib/triviacrack/api/common.rb, line 49
def default_headers
  headers = { "Content-Type": "application/json; charset=utf-8" }

  if @session
    headers["Cookie"] = "ap_session=#{@session.session_id}"
  end

  headers
end