module Castle::Core::ProcessResponse

parses api response

Constants

INVALID_REQUEST_TOKEN
RESPONSE_ERRORS

Public Class Methods

call(response, config = nil) click to toggle source

@param response [Response] @param config [Castle::Configuration, Castle::SingletonConfiguration, nil] @return [Hash]

# File lib/castle/core/process_response.rb, line 22
def call(response, config = nil)
  verify!(response)

  Castle::Logger.call('response:', response.body.to_s, config)

  return {} if response.body.nil? || response.body.empty?

  begin
    JSON.parse(response.body, symbolize_names: true)
  rescue JSON::ParserError
    raise Castle::ApiError, 'Invalid response from Castle API'
  end
end
raise_error422(response) click to toggle source
# File lib/castle/core/process_response.rb, line 48
def raise_error422(response)
  if response.body
    begin
      parsed_body = JSON.parse(response.body, symbolize_names: true)
      if parsed_body.is_a?(Hash) && parsed_body.key?(:type)
        if parsed_body[:type] == INVALID_REQUEST_TOKEN
          raise Castle::InvalidRequestTokenError, parsed_body[:message]
        end

        raise Castle::InvalidParametersError, parsed_body[:message]
      end
    rescue JSON::ParserError
    end
  end

  raise Castle::InvalidParametersError
end
verify!(response) click to toggle source
# File lib/castle/core/process_response.rb, line 36
def verify!(response)
  return if response.code.to_i.between?(200, 299)

  raise Castle::InternalServerError if response.code.to_i.between?(500, 599)

  raise_error422(response) if response.code.to_i == 422

  error = RESPONSE_ERRORS.fetch(response.code.to_i, Castle::ApiError)

  raise error
end