Sha256: d60f7091877fb0960cf0358d1f075985da1c0376121a9ad2a2c9f2aec64d4780

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

module Copy
  module Request
    class Validator
      attr_reader :info
      attr_accessor :response

      def initialize(info)
        @info = info
      end

      def validated_data_for(incoming_response)
        self.response = incoming_response
        verify_response_code
        info.data = JSON.parse(response.body) if response.code.to_i != 204
        info.data ||= {}
        validate_response_data
        info.data
      end

      protected

      def verify_response_code
        raise AuthenticationError if response.code.to_i == 401
        raise APIError if response.code.to_i >= 500
        raise NotFound if response.code.to_i >= 404
      end

      def validate_response_data
        body ||= info.data
        if body.is_a?(Hash)
          if body['error']
            handle_api_error(body['error'], body['message'])
          elsif body['errors']
            body['errors'].each do |error|
              handle_api_error(error['code'], error['message'])
            end
          end
        end
      end

      def handle_api_error(code, message)
        error = case code
                when 1021, 1024  then ObjectNotFound.new(message)
                when 1300, 1303  then BadRequest.new(message)
                when 2000        then AuthenticationError.new(message)
                else
                  APIError.new(message)
                end
        fail error
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
copy-ruby-0.0.2 lib/copy/request/validator.rb