Merge pull request #5469 from NARKOZ/api-pagination-headers
add 'Link' header for API response
This commit is contained in:
commit
046fa9bdb1
2 changed files with 24 additions and 2 deletions
|
@ -56,8 +56,12 @@ module API
|
|||
end
|
||||
end
|
||||
|
||||
def paginate(object)
|
||||
object.page(params[:page]).per(params[:per_page].to_i)
|
||||
def paginate(relation)
|
||||
per_page = params[:per_page].to_i
|
||||
paginated = relation.page(params[:page]).per(per_page)
|
||||
add_pagination_headers(paginated, per_page)
|
||||
|
||||
paginated
|
||||
end
|
||||
|
||||
def authenticate!
|
||||
|
@ -134,6 +138,18 @@ module API
|
|||
|
||||
private
|
||||
|
||||
def add_pagination_headers(paginated, per_page)
|
||||
request_url = request.url.split('?').first
|
||||
|
||||
links = []
|
||||
links << %(<#{request_url}?page=#{paginated.current_page - 1}&per_page=#{per_page}>; rel="prev") unless paginated.first_page?
|
||||
links << %(<#{request_url}?page=#{paginated.current_page + 1}&per_page=#{per_page}>; rel="next") unless paginated.last_page?
|
||||
links << %(<#{request_url}?page=1&per_page=#{per_page}>; rel="first")
|
||||
links << %(<#{request_url}?page=#{paginated.total_pages}&per_page=#{per_page}>; rel="last")
|
||||
|
||||
header 'Link', links.join(', ')
|
||||
end
|
||||
|
||||
def abilities
|
||||
@abilities ||= begin
|
||||
abilities = Six.new
|
||||
|
|
|
@ -25,6 +25,12 @@ describe API::API do
|
|||
json_response.should be_an Array
|
||||
json_response.first['title'].should == issue.title
|
||||
end
|
||||
|
||||
it "should add pagination headers" do
|
||||
get api("/issues?per_page=3", user)
|
||||
response.headers['Link'].should ==
|
||||
'<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"'
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in a new issue