Sha256: cb3e0622cc432c0fe5f2597604830d558990bdb4a85461d24c115d08171a6c47

Contents?: true

Size: 1.37 KB

Versions: 10

Compression:

Stored size: 1.37 KB

Contents

require 'httparty'
require 'dry-struct'
require 'dry-types'

module Nova
  module API
    class ListResponse < Nova::API::Utils::BaseStruct
      attribute :records, Dry::Types['strict.array'].of(Dry::Types['nominal.any']).optional
      attribute :errors, Dry::Types['strict.array'].of(Dry::Types['coercible.string'])
      attribute :success, Dry::Types['strict.bool']
      attribute :status, Dry::Types['coercible.integer']

      def self.build(response, klass)
        success = response.success?
        status = response.code

        parsed_response = response.parsed_response

        records = nil

        if parsed_response.is_a?(Array)
          records = build_records(klass, parsed_response)
        else
          parsed_response = parsed_response.to_h

          errors = extract_error_from_response('error', parsed_response)
          errors ||= extract_error_from_response('errors', parsed_response)
        end

        errors ||= []

        new(success: success, errors: errors, records: records, status: status)
      end

      private

      def self.extract_error_from_response(field, response)
        return unless response.has_key?(field)

        response[field].is_a?(Array) ? response[field] : [response[field]]
      end

      def self.build_records(klass, response)
        response.map { |object| klass.new(object) } unless klass.nil?
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
nova-api-1.4.6 lib/nova/api/list_response.rb
nova-api-1.4.5 lib/nova/api/list_response.rb
nova-api-1.4.3 lib/nova/api/list_response.rb
nova-api-1.4.1 lib/nova/api/list_response.rb
nova-api-1.4.0 lib/nova/api/list_response.rb
nova-api-1.3.0 lib/nova/api/list_response.rb
nova-api-1.2.0 lib/nova/api/list_response.rb
nova-api-1.1.0 lib/nova/api/list_response.rb
nova-api-1.0.0 lib/nova/api/list_response.rb
nova-api-0.8.0 lib/nova/api/list_response.rb