Sha256: 85c8dc4bd800f92d1e97403577578a2f4a7ca4ea4bcdac9aefa4052b156c8219

Contents?: true

Size: 1.46 KB

Versions: 8

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

module BeyondApi
  module Utils
    extend self

    def handle_response(response, status, respond_with_true: false)
      if status.between?(200, 299)
        return true if respond_with_true
        response = sanitize_response(response)
        BeyondApi.configuration.object_struct_responses ? to_object_struct(response) : response
      else
        error = BeyondApi::Error.new(response)
        BeyondApi.logger.error "[Beyond API] #{response}"
        BeyondApi.configuration.raise_error_requests ? raise(error) : error
      end
    end

    def to_object_struct(data)
      if data.is_a? Hash
        return OpenStruct.new(data.map { |key, val| [key, to_object_struct(val)] }.to_h)
      elsif data.is_a? Array
        return data.map { |o| to_object_struct(o) }
      else
        return data
      end
    end

    def sanitize_response(hash)
      {}.tap do |h|
        hash.each do |key, value|
          next if key == "_links" && BeyondApi.configuration.remove_response_links
          key = sanitize_key(key) if BeyondApi.configuration.remove_response_key_underscores
          h[key.underscore.to_sym] = transform(value)
        end
      end
    end

    def sanitize_key(key)
      key.chars.first == "_" ? key[1..-1] : key
    end

    private

      def transform(thing)
        case thing
        when Hash; sanitize_response(thing)
        when Array; thing.map { |v| transform(v) }
        else; thing
        end
      end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
beyond_api-0.8.0.pre lib/beyond_api/utils.rb
beyond_api-0.7.1.pre lib/beyond_api/utils.rb
beyond_api-0.7.0.pre lib/beyond_api/utils.rb
beyond_api-0.6.0.pre lib/beyond_api/utils.rb
beyond_api-0.5.1.pre lib/beyond_api/utils.rb
beyond_api-0.5.0.pre lib/beyond_api/utils.rb
beyond_api-0.4.0.pre lib/beyond_api/utils.rb
beyond_api-0.3.0.pre lib/beyond_api/utils.rb