gitlab-org--gitlab-foss/lib/bitbucket_server/paginator.rb
Stan Hu 5b6d5301d9 Paginate Bitbucket Server importer projects
To prevent delays in loading the page and reduce memory usage, limit the
number of projects shown at 25 per page.

Part of https://gitlab.com/gitlab-org/gitlab-ce/issues/50021
2018-11-07 11:37:46 -08:00

53 lines
1.1 KiB
Ruby

# 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 || PAGE_LENGTH
@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?
@limit.positive? && @total >= @limit
end
def next_offset
page.nil? ? starting_offset : page.next
end
def starting_offset
[0, page_offset - 1].max * limit
end
def fetch_next_page
parsed_response = connection.get(@url, start: next_offset, limit: @limit)
Page.new(parsed_response, type)
end
end
end