Sha256: 7d70de3459048a68b604a7e655847f0d79326e44dab39c7b1496eef1ee23cf5d

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

require 'net/http'
require 'uri'

module Tikkie
  module Api
    # Parses and wraps the response from the Tikkie 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
      end

      def error?
        !success?
      end

      def invalid?
        body.nil?
      end

      def request_uri
        response.uri
      end

      def http_code
        response.code.to_i
      end

      def http_message
        response.message
      end

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

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

          errors
        end
      end

      private

      def parse_body(body)
        JSON.parse(body, symbolize_names: true)
      rescue JSON::ParserError
        nil
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tikkie-api-2.0.0 lib/tikkie/api/response.rb