Last active
August 29, 2015 13:57
-
-
Save jadehopepunk/9609833 to your computer and use it in GitHub Desktop.
output more logging stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Xeroizer | |
module Http | |
private | |
def http_request(client, method, url, body, params = {}) | |
# headers = {'Accept-Encoding' => 'gzip, deflate'} | |
headers = { 'charset' => 'utf-8' } | |
if method != :get | |
headers['Content-Type'] ||= "application/x-www-form-urlencoded" | |
end | |
content_type = params.delete(:content_type) | |
headers['Content-Type'] = content_type if content_type | |
# HAX. Xero completely misuse the If-Modified-Since HTTP header. | |
headers['If-Modified-Since'] = params.delete(:ModifiedAfter).utc.strftime("%Y-%m-%dT%H:%M:%S") if params[:ModifiedAfter] | |
# Allow 'Accept' header to be specified with :accept parameter. | |
# Valid values are :pdf or :json. | |
if params[:response] | |
response_type = params.delete(:response) | |
headers['Accept'] = case response_type | |
when Symbol then ACCEPT_MIME_MAP[response_type] | |
else response_type | |
end | |
end | |
if params.any? | |
url += "?" + params.map {|key,value| "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}"}.join("&") | |
end | |
uri = URI.parse(url) | |
attempts = 0 | |
begin | |
attempts += 1 | |
puts("XeroGateway Request: #{method.to_s.upcase} #{uri.request_uri}: #{body}") | |
raw_body = params.delete(:raw_body) ? body : {:xml => body} | |
response = case method | |
when :get then client.get(uri.request_uri, headers) | |
when :post then client.post(uri.request_uri, raw_body, headers) | |
when :put then client.put(uri.request_uri, raw_body, headers) | |
end | |
if self.logger | |
logger.info("XeroGateway Response (#{response.code})") | |
puts("#{uri.request_uri}\n== Response Body\n\n#{response.plain_body}\n== End Response Body") | |
unless response.code.to_i == 200 | |
end | |
end | |
case response.code.to_i | |
when 200 | |
response.plain_body | |
when 400 | |
handle_error!(response, body) | |
when 401 | |
handle_oauth_error!(response) | |
when 404 | |
handle_object_not_found!(response, url) | |
when 503 | |
handle_oauth_error!(response) | |
else | |
handle_unknown_response_error!(response) | |
end | |
rescue Xeroizer::OAuth::RateLimitExceeded | |
if self.rate_limit_sleep | |
raise if attempts > rate_limit_max_attempts | |
logger.info("Rate limit exceeded, retrying") if self.logger | |
sleep_for(self.rate_limit_sleep) | |
retry | |
else | |
raise | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment