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, config = nil) ⇒ Hash

Parameters:

Returns:

  • (Hash)
[View source]

20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/castle/core/process_response.rb', line 20

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

.verify!(response) ⇒ Object

[View source]

34
35
36
37
38
39
40
41
# File 'lib/castle/core/process_response.rb', line 34

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