Skip to content

Commit 16e5204

Browse files
Always include pagination keys but set null values when not needed
1 parent ff71ef2 commit 16e5204

File tree

1 file changed

+27
-27
lines changed

1 file changed

+27
-27
lines changed

lib/active_model_serializers/adapter/json_api/pagination_links.rb

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ module Adapter
33
class JsonApi < Base
44
class PaginationLinks
55
MissingSerializationContextError = Class.new(KeyError)
6-
FIRST_PAGE = 1
76

87
attr_reader :collection, :context
98

@@ -20,12 +19,13 @@ def initialize(collection, adapter_options)
2019
end
2120

2221
def as_json
23-
per_page = collection.try(:per_page) || collection.try(:limit_value) || collection.size
24-
pages_from.each_with_object({}) do |(key, value), hash|
25-
params = query_parameters.merge(page: { number: value, size: per_page }).to_query
26-
27-
hash[key] = "#{url(adapter_options)}?#{params}"
28-
end
22+
{
23+
"self": location_url,
24+
"first": first_page_url,
25+
"prev": prev_page_url,
26+
"next": next_page_url,
27+
"last": last_page_url
28+
}
2929
end
3030

3131
protected
@@ -34,37 +34,37 @@ def as_json
3434

3535
private
3636

37-
def pages_from
38-
{}.tap do |pages|
39-
pages[:self] = collection.current_page
40-
pages[:first] = FIRST_PAGE
41-
pages[:last] = collection.total_pages
37+
def location_url
38+
url_for_page(collection.current_page)
39+
end
4240

43-
if collection.total_pages > 0
44-
unless collection.current_page == FIRST_PAGE
45-
pages[:prev] = collection.current_page - FIRST_PAGE
46-
end
41+
def first_page_url
42+
url_for_page(1)
43+
end
4744

48-
unless collection.current_page == collection.total_pages
49-
pages[:next] = collection.current_page + FIRST_PAGE
50-
end
51-
else
52-
pages[:last] = FIRST_PAGE
53-
end
54-
end
45+
def prev_page_url
46+
return nil if collection.first_page?
47+
url_for_page(collection.prev_page)
5548
end
5649

57-
def url(options)
58-
@url ||= options.fetch(:links, {}).fetch(:self, nil) || request_url
50+
def next_page_url
51+
return nil if collection.last_page? || collection.out_of_range?
52+
url_for_page(collection.next_page)
5953
end
6054

61-
def request_url
62-
@request_url ||= context.request_url
55+
def url_for_page(number)
56+
params = query_parameters.dup
57+
params[:page] = { page: per_page, number: number }
58+
context.url_for(action: :index, params: params)
6359
end
6460

6561
def query_parameters
6662
@query_parameters ||= context.query_parameters
6763
end
64+
65+
def per_page
66+
@per_page ||= collection.try(:per_page) || collection.try(:limit_value) || collection.size
67+
end
6868
end
6969
end
7070
end

0 commit comments

Comments
 (0)