Commit 046fa9bdb106f4a94b3f62646726e99923e75b0a
Exists in
spb-stable
and in
3 other branches
Merge pull request #5469 from NARKOZ/api-pagination-headers
add 'Link' header for API response
Showing
2 changed files
with
24 additions
and
2 deletions
Show diff stats
lib/api/helpers.rb
... | ... | @@ -56,8 +56,12 @@ module API |
56 | 56 | end |
57 | 57 | end |
58 | 58 | |
59 | - def paginate(object) | |
60 | - object.page(params[:page]).per(params[:per_page].to_i) | |
59 | + def paginate(relation) | |
60 | + per_page = params[:per_page].to_i | |
61 | + paginated = relation.page(params[:page]).per(per_page) | |
62 | + add_pagination_headers(paginated, per_page) | |
63 | + | |
64 | + paginated | |
61 | 65 | end |
62 | 66 | |
63 | 67 | def authenticate! |
... | ... | @@ -134,6 +138,18 @@ module API |
134 | 138 | |
135 | 139 | private |
136 | 140 | |
141 | + def add_pagination_headers(paginated, per_page) | |
142 | + request_url = request.url.split('?').first | |
143 | + | |
144 | + links = [] | |
145 | + links << %(<#{request_url}?page=#{paginated.current_page - 1}&per_page=#{per_page}>; rel="prev") unless paginated.first_page? | |
146 | + links << %(<#{request_url}?page=#{paginated.current_page + 1}&per_page=#{per_page}>; rel="next") unless paginated.last_page? | |
147 | + links << %(<#{request_url}?page=1&per_page=#{per_page}>; rel="first") | |
148 | + links << %(<#{request_url}?page=#{paginated.total_pages}&per_page=#{per_page}>; rel="last") | |
149 | + | |
150 | + header 'Link', links.join(', ') | |
151 | + end | |
152 | + | |
137 | 153 | def abilities |
138 | 154 | @abilities ||= begin |
139 | 155 | abilities = Six.new | ... | ... |
spec/requests/api/issues_spec.rb
... | ... | @@ -25,6 +25,12 @@ describe API::API do |
25 | 25 | json_response.should be_an Array |
26 | 26 | json_response.first['title'].should == issue.title |
27 | 27 | end |
28 | + | |
29 | + it "should add pagination headers" do | |
30 | + get api("/issues?per_page=3", user) | |
31 | + response.headers['Link'].should == | |
32 | + '<http://www.example.com/api/v3/issues?page=1&per_page=3>; rel="first", <http://www.example.com/api/v3/issues?page=1&per_page=3>; rel="last"' | |
33 | + end | |
28 | 34 | end |
29 | 35 | end |
30 | 36 | ... | ... |