Sha256: 66ea886501549569abb57036849a2e1896b5ed2a3c24454e076bbce669ba3152

Contents?: true

Size: 1.06 KB

Versions: 7

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

require 'json'

module Kentaa
  module Api
    class Response
      attr_reader :response, :body

      def initialize(response)
        @response = response
        @body = response.body ? parse_body(response.body) : {}
      end

      def success?
        (http_code == 200 || http_code == 201 || http_code == 204) && !message
      end

      def error?
        !success?
      end

      def http_code
        response.code.to_i
      end

      def request_uri
        response.uri
      end

      def message
        body[:message]
      end

      def errors
        @errors ||= begin
          errors = []

          if body[:errors]
            body[:errors].each do |error|
              errors << Kentaa::Api::Resources::Error.new(error)
            end
          end

          errors
        end
      end

      private

      def parse_body(body)
        JSON.parse(body, symbolize_names: true)
      rescue JSON::ParserError => e
        {
          message: "Unable to parse JSON: #{e.message}"
        }
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
kentaa-api-0.8.0 lib/kentaa/api/response.rb
kentaa-api-0.7.2 lib/kentaa/api/response.rb
kentaa-api-0.7.1 lib/kentaa/api/response.rb
kentaa-api-0.7.0 lib/kentaa/api/response.rb
kentaa-api-0.6.0 lib/kentaa/api/response.rb
kentaa-api-0.5.0 lib/kentaa/api/response.rb
kentaa-api-0.4.0 lib/kentaa/api/response.rb