Sha256: e3c6657ac65c58cc5d82f832c21b40fb66764d5206c15a9dde2fc7c87386ffaa

Contents?: true

Size: 1.83 KB

Versions: 3

Compression:

Stored size: 1.83 KB

Contents

# Understands how to represent the result of a request to the Pipedrive API
module Pipekit
  class Result

    def initialize(resource, response_data)
      @response_data = response_data
      @resource = resource
      raise UnsuccessfulRequestError.new(response_data) unless success?
    end

    def response
      raise ResourceNotFoundError.new(response_data) unless resource_found?
      return Response.new(resource, response_body) unless response_body.is_a? Array
      response_body.map { |data| Response.new(resource, data) }
    end

    def +(other)
      self.class.new(resource, other.merged_response(response_body))
    end

    def fetch_next_request?
      Config.fetch(:request_all_pages, true) && pagination_data["more_items_in_collection"]
    end

    def next_start
      pagination_data["next_start"]
    end

    def self.response(resource, response_data)
      new(resource, response_data).response
    end

    protected

    def merged_response(other_body)
      response_data.tap do |response|
        response["data"] = other_body + response_body
      end
    end

    private

    attr_reader :response_data, :resource

    def pagination_data
      response_data
        .fetch("additional_data", {})
        .fetch("pagination", {})
    end

    def response_body
      response_data["data"]
    end

    def success?
      response_data["success"]
    end

    def resource_found?
      !(response_body.nil? || response_body.empty?)
    end
  end

  class ResourceNotFoundError < StandardError
    def initialize(response)
      @response = response
    end

    def message
      "Resource not found, response was: #{@response}"
    end
  end

  class UnsuccessfulRequestError < StandardError
    def initialize(response)
      @response = response
    end

    def message
      "Request not successful: #{@response}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pipekit-2.1.1 lib/pipekit/result.rb
pipekit-2.0.0 lib/pipekit/result.rb
pipekit-1.2.0 lib/pipekit/result.rb