Read about our upcoming Code of Conduct on this issue

page.rb 1.29 KB
Newer Older
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
# frozen_string_literal: true

module Gitlab
  module Pagination
    module Keyset
      # A Page models the pagination information for a particular page of the collection
      class Page
        # Default and maximum size of records for a page
        DEFAULT_PAGE_SIZE = 20

        attr_accessor :lower_bounds, :end_reached
        attr_reader :order_by

        def initialize(order_by: {}, lower_bounds: nil, per_page: DEFAULT_PAGE_SIZE, end_reached: false)
          @order_by = order_by.symbolize_keys
          @lower_bounds = lower_bounds&.symbolize_keys
          @per_page = per_page
          @end_reached = end_reached
        end

        # Number of records to return per page
        def per_page
          return DEFAULT_PAGE_SIZE if @per_page <= 0

          [@per_page, DEFAULT_PAGE_SIZE].min
        end

        # Determine whether this page indicates the end of the collection
        def end_reached?
          @end_reached
        end

        # Construct a Page for the next page
        # Uses identical order_by/per_page information for the next page
        def next(lower_bounds, end_reached)
          dup.tap do |next_page|
            next_page.lower_bounds = lower_bounds&.symbolize_keys
            next_page.end_reached = end_reached
          end
        end
      end
    end
  end
end