2024-04-17 11:22:45 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Api::Pagination
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2024-05-30 16:56:48 +02:00
|
|
|
PAGINATION_PARAMS = %i(limit).freeze
|
|
|
|
|
2024-04-17 11:22:45 +02:00
|
|
|
protected
|
|
|
|
|
|
|
|
def pagination_max_id
|
|
|
|
pagination_collection.last.id
|
|
|
|
end
|
|
|
|
|
|
|
|
def pagination_since_id
|
|
|
|
pagination_collection.first.id
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_pagination_headers(next_path = nil, prev_path = nil)
|
|
|
|
links = []
|
|
|
|
links << [next_path, [%w(rel next)]] if next_path
|
|
|
|
links << [prev_path, [%w(rel prev)]] if prev_path
|
2024-09-05 22:05:38 +02:00
|
|
|
response.headers['Link'] = LinkHeader.new(links).to_s unless links.empty?
|
2024-04-17 11:22:45 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def require_valid_pagination_options!
|
|
|
|
render json: { error: 'Pagination values for `offset` and `limit` must be positive' }, status: 400 if pagination_options_invalid?
|
|
|
|
end
|
|
|
|
|
2024-05-30 16:56:48 +02:00
|
|
|
def pagination_params(core_params)
|
|
|
|
params
|
|
|
|
.slice(*PAGINATION_PARAMS)
|
|
|
|
.permit(*PAGINATION_PARAMS)
|
|
|
|
.merge(core_params)
|
|
|
|
end
|
|
|
|
|
2024-04-17 11:22:45 +02:00
|
|
|
private
|
|
|
|
|
|
|
|
def insert_pagination_headers
|
|
|
|
set_pagination_headers(next_path, prev_path)
|
|
|
|
end
|
|
|
|
|
|
|
|
def pagination_options_invalid?
|
|
|
|
params.slice(:limit, :offset).values.map(&:to_i).any?(&:negative?)
|
|
|
|
end
|
|
|
|
end
|