Class: X::ResponseParser

Inherits:
Object
  • Object
show all
Defined in:
lib/x/response_parser.rb

Overview

Parses HTTP responses from the X API

Constant Summary collapse

ERROR_MAP =

Mapping of HTTP status codes to error classes

{
  400 => BadRequest,
  401 => Unauthorized,
  403 => Forbidden,
  404 => NotFound,
  406 => NotAcceptable,
  409 => ConnectionException,
  410 => Gone,
  413 => PayloadTooLarge,
  422 => UnprocessableEntity,
  429 => TooManyRequests,
  500 => InternalServerError,
  502 => BadGateway,
  503 => ServiceUnavailable,
  504 => GatewayTimeout
}.freeze

Instance Method Summary collapse

Instance Method Details

#parse(response:, array_class: nil, object_class: nil) ⇒ Hash, ...

Parse an HTTP response

Examples:

Parse a response

parser.parse(response: response)

Parameters:

  • response (Net::HTTPResponse)

    the HTTP response to parse

  • array_class (Class, nil) (defaults to: nil)

    the class for parsing JSON arrays

  • object_class (Class, nil) (defaults to: nil)

    the class for parsing JSON objects

Returns:

  • (Hash, Array, nil)

    the parsed response body

Raises:

  • (HTTPError)

    if the response is not successful



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/x/response_parser.rb', line 51

def parse(response:, array_class: nil, object_class: nil)
  raise error(response) unless response.is_a?(Net::HTTPSuccess)

  return if response.instance_of?(Net::HTTPNoContent)

  begin
    JSON.parse(response.body, array_class:, object_class:)
  rescue JSON::ParserError
    nil
  end
end