Skip to content

Instantly share code, notes, and snippets.

@ammancilla
Created January 25, 2021 21:26
Show Gist options
  • Save ammancilla/7f4d40dafc14493d7f29a61e2692a342 to your computer and use it in GitHub Desktop.
Save ammancilla/7f4d40dafc14493d7f29a61e2692a342 to your computer and use it in GitHub Desktop.
API WRAPPER
require 'net/http'
module APIWrapper
class ServiceUnavailable < StandardError; end
class BadGateway < StandardError; end
class GatewayTimeOut < StandardError; end
class UnknownResponse < StandardError; end
class InvalidResponse < StandardError; end
class ExternalServerError < StandardError; end
class BadRequest < StandardError; end
class Unauthorized < StandardError; end
HTTP_STATUS_TO_ERRORS = {
400 => BadRequest,
401 => Unauthorized,
500 => ExternalServerError,
502 => BadGateway,
503 => ServiceUnavailable,
504 => GatewayTimeOut
}.freeze
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def api_root(root)
class_variable_set :@@root, root
end
private
def get(path, _params: {}, _headers: {})
uri = uri_for(path)
response = Net::HTTP.get_response(uri)
response_handler(response)
end
def post(path, params: {}, _headers: {})
uri = uri_for(path)
response = Net::HTTP.post_form(uri, params)
response_handler(response)
end
def uri_for(path)
root = class_variable_get :@@root
raise 'Missing API root' if root.nil?
URI("#{root}/#{path}")
end
def response_handler(response)
response_code = response.code.to_i
response_type = response.content_type
response_body = response.body
raise(InvalidResponse, response.body) if response_type != 'application/json'
case response_code
when 200, 204
JSON.parse(response_body) if response_body.present?
when *HTTP_STATUS_TO_ERRORS.keys
error_class = HTTP_STATUS_TO_ERRORS[response_code]
raise error_class, response_body
else
raise UnknownResponse, response_body
end
rescue JSON::ParserError
raise InvalidResponse, response_body
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment