Sha256: fe00b2d79cc74e88c63b1d6dbdab611cb46116befad791cec962a6ef354b03c8

Contents?: true

Size: 1.01 KB

Versions: 2

Compression:

Stored size: 1.01 KB

Contents

module CurrencyCloud
  
  class ResponseHandler
    
    attr_reader :verb, :route, :params, :response
    
    def initialize(verb, route, params, response)
      @verb = verb
      @route = route
      @params = params
      @response = response
    end
    
    def process
      if success?
        return parsed_response
      else
        handle_failure
      end
    end
    
    private
    
    def success?
      [200, 202].include?(response.code)
    end
    
    def handle_failure
      error_class = case response.code
        when 400 then BadRequestError
        when 401 then AuthenticationError
        when 403 then ForbiddenError
        when 404 then NotFoundError
        when 429 then TooManyRequestsError
        when 500 then InternalApplicationError
      end
      raise error_class.new(verb, route, params, response) if error_class
      raise UnexpectedError.new(verb, route, params, response)
    end
    
    def parsed_response
      @parsed_response ||= JSON.parse(response.body)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
currency_cloud-0.7.1 lib/currency_cloud/response_handler.rb
currency_cloud-0.7 lib/currency_cloud/response_handler.rb