Sha256: 242701e537cba02eddecf33115f98e3f7ac647753e3daae70e619aa84b1f03b2

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module Talkbird
  module Result
    # A variation of the result which should support composition.
    class PaginatedSuccess

      class << self

        def deep_merge(data, elem)
          data.merge(elem) do |key, oldval, newval|
            if key == :next
              nil
            else
              oldval + newval
            end
          end
        end

      end

      def initialize(result)
        @result = result
      end

      def reduce
        body = compose.reduce({}) { |data, el| PaginatedSuccess.deep_merge(data, el.body) }
        response = HTTP::Response.new(
          status: @result.status,
          version: @result.version,
          body: MultiJson.dump(body),
          headers: @result.headers
        )

        Result::Success.new(response, body)
      end

      def compose
        body = MultiJson.load(@result.body.to_s, symbolize_keys: true)
        token = body[:next].to_s

        if !token.empty?
          [
            Result::Success.new(@result, body),
            next_page(token)
          ].flatten
        else
          [Result::Success.new(@result, body)]
        end
      end

      def next_page(token)
        Talkbird::Client.request(
          :get,
          @result.uri,
          params: { token: token, limit: 100 }
        )
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
talkbird-0.0.5 lib/talkbird/result/paginated_success.rb
talkbird-0.0.4 lib/talkbird/result/paginated_success.rb
talkbird-0.0.3 lib/talkbird/result/paginated_success.rb
talkbird-0.0.2 lib/talkbird/result/paginated_success.rb