class Camp3::Request
@private
Public Class Methods
decode(response)
click to toggle source
Decodes a JSON response into Ruby object.
# File lib/camp3/request.rb, line 47 def self.decode(response) response ? JSON.load(response) : {} rescue JSON::ParserError raise Error::Parsing, 'The response is not a valid JSON' end
new(access_token, user_agent, client)
click to toggle source
# File lib/camp3/request.rb, line 20 def initialize(access_token, user_agent, client) @access_token = access_token @client = client self.class.headers 'User-Agent' => user_agent end
parse(body)
click to toggle source
Converts the response body to a Resource
.
# File lib/camp3/request.rb, line 28 def self.parse(body) body = decode(body) if body.is_a? Hash Resource.create(body) elsif body.is_a? Array PaginatedResponse.new(body.collect! { |e| Resource.create(e) }) elsif body true elsif !body false elsif body.nil? false else raise Error::Parsing, "Couldn't parse a response body" end end
Private Instance Methods
execute_request(method, endpoint, params)
click to toggle source
Executes the request
# File lib/camp3/request.rb, line 69 def execute_request(method, endpoint, params) params[:headers].merge!(self.class.headers) params[:headers].merge!(authorization_header) logger.debug("Method: #{method}; URL: #{endpoint}") response, result = validate self.class.send(method, endpoint, params) response = extract_parsed(response) if result == Result::Valid return response, result end
extract_parsed(response)
click to toggle source
# File lib/camp3/request.rb, line 98 def extract_parsed(response) parsed = response.parsed_response parsed.client = @client if parsed.respond_to?(:client=) parsed.parse_headers!(response.headers) if parsed.respond_to?(:parse_headers!) parsed end
validate(response)
click to toggle source
Checks the response code for common errors. Informs that a retry needs to happen if request failed due to access token expiration @raise [Error::ResponseError] if response is an HTTP error @return [Response, Request::Result]
# File lib/camp3/request.rb, line 85 def validate(response) error_klass = Error::STATUS_MAPPINGS[response.code] if error_klass == Error::Unauthorized && response.parsed_response.error.include?("OAuth token expired (old age)") logger.debug("Access token expired. Please obtain a new access token") return response, Result::AccessTokenExpired end raise error_klass, response if error_klass return response, Result::Valid end