summaryrefslogtreecommitdiff
path: root/lib/bitbucket_server/paginator.rb
blob: 8a4943798642cd628b166e41010272a5ba32a9f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

module BitbucketServer
  class Paginator
    PAGE_LENGTH = 25

    attr_reader :page_offset

    def initialize(connection, url, type, page_offset: 0, limit: nil)
      @connection = connection
      @type = type
      @url = url
      @page = nil
      @page_offset = page_offset
      @limit = limit
      @total = 0
    end

    def items
      raise StopIteration unless has_next_page?
      raise StopIteration if over_limit?

      @page = fetch_next_page
      @total += @page.items.count
      @page.items
    end

    def has_next_page?
      page.nil? || page.next?
    end

    private

    attr_reader :connection, :page, :url, :type, :limit

    def over_limit?
      return false unless @limit

      @limit > 0 && @total >= @limit
    end

    def next_offset
      page.nil? ? starting_offset : page.next
    end

    def starting_offset
      [0, page_offset - 1].max * max_per_page
    end

    def max_per_page
      limit || PAGE_LENGTH
    end

    def fetch_next_page
      parsed_response = connection.get(@url, start: next_offset, limit: max_per_page)
      Page.new(parsed_response, type)
    end
  end
end