Module: Castle::Core::ProcessResponse

Defined in:
lib/castle/core/process_response.rb

Overview

parses api response

Constant Summary collapse

RESPONSE_ERRORS =
{
  400 => Castle::BadRequestError,
  401 => Castle::UnauthorizedError,
  403 => Castle::ForbiddenError,
  404 => Castle::NotFoundError,
  419 => Castle::UserUnauthorizedError,
  422 => Castle::InvalidParametersError
}.freeze

Class Method Summary collapse

Class Method Details

.call(response) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/castle/core/process_response.rb', line 17

def call(response)
  verify!(response)

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

  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

.verify!(response) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/castle/core/process_response.rb', line 31

def verify!(response)
  return if response.code.to_i.between?(200, 299)

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

  error = RESPONSE_ERRORS.fetch(response.code.to_i, Castle::ApiError)
  raise error, response[:message]
end