Sha256: a52b9698b05d205777ac44ae056bf4a7abfc7c70d9e98c73ff5282fc3327fa43

Contents?: true

Size: 1.89 KB

Versions: 14

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

module Telnyx
  # TelnyxResponse encapsulates some vitals of a response that came back from
  # the Telnyx API.
  class TelnyxResponse
    # The data contained by the HTTP body of the response deserialized from
    # JSON.
    attr_accessor :data

    # The raw HTTP body of the response.
    attr_accessor :http_body

    # A Hash of the HTTP headers of the response.
    attr_accessor :http_headers

    # The integer HTTP status code of the response.
    attr_accessor :http_status

    # The Telnyx request ID of the response.
    attr_accessor :request_id

    # Initializes a TelnyxResponse object from a Hash like the kind returned as
    # part of a Faraday exception.
    #
    # This may throw JSON::ParserError if the response body is not valid JSON.
    def self.from_faraday_hash(http_resp)
      resp = TelnyxResponse.new
      resp.data = JSON.parse(preprocess_response(http_resp[:body]), symbolize_names: true)
      resp.http_body = http_resp[:body]
      resp.http_headers = http_resp[:headers]
      resp.http_status = http_resp[:status]
      resp.request_id = http_resp[:headers]["X-Request-Id"]
      resp
    end

    # Initializes a TelnyxResponse object from a Faraday HTTP response object.
    #
    # This may throw JSON::ParserError if the response body is not valid JSON.
    def self.from_faraday_response(http_resp)
      resp = TelnyxResponse.new
      resp.data = JSON.parse(preprocess_response(http_resp.body), symbolize_names: true)
      resp.http_body = http_resp.body
      resp.http_headers = http_resp.headers
      resp.http_status = http_resp.status
      resp.request_id = http_resp.headers["X-Request-Id"]
      resp
    end

    class << self
      private

      # Helper to handle when the server responds with a blank body (as is the case with SimCards).
      def preprocess_response(resp)
        resp.empty? ? "{}" : resp
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
telnyx-3.0.3 lib/telnyx/telnyx_response.rb
telnyx-3.0.2 lib/telnyx/telnyx_response.rb
telnyx-3.0.0 lib/telnyx/telnyx_response.rb
telnyx-2.9.0 lib/telnyx/telnyx_response.rb
telnyx-2.8.0 lib/telnyx/telnyx_response.rb
telnyx-2.7.0 lib/telnyx/telnyx_response.rb
telnyx-2.6.0 lib/telnyx/telnyx_response.rb
telnyx-2.5.0 lib/telnyx/telnyx_response.rb
telnyx-2.4.0 lib/telnyx/telnyx_response.rb
telnyx-2.3.0 lib/telnyx/telnyx_response.rb
telnyx-2.2.0 lib/telnyx/telnyx_response.rb
telnyx-0.1.0 lib/telnyx/telnyx_response.rb
telnyx-0.0.8 lib/telnyx/telnyx_response.rb
telnyx-0.0.7 lib/telnyx/telnyx_response.rb