Commit 0678b8a426553110e63dde3c75aaf719e74771e1
1 parent
ff7073ac
Exists in
spb-stable
and in
3 other branches
add 'Link' header for API response
Showing
2 changed files
with
24 additions
and
2 deletions
Show diff stats
lib/api/helpers.rb
| @@ -51,8 +51,12 @@ module API | @@ -51,8 +51,12 @@ module API | ||
| 51 | end | 51 | end |
| 52 | end | 52 | end |
| 53 | 53 | ||
| 54 | - def paginate(object) | ||
| 55 | - object.page(params[:page]).per(params[:per_page].to_i) | 54 | + def paginate(relation) |
| 55 | + per_page = params[:per_page].to_i | ||
| 56 | + paginated = relation.page(params[:page]).per(per_page) | ||
| 57 | + add_pagination_headers(paginated, per_page) | ||
| 58 | + | ||
| 59 | + paginated | ||
| 56 | end | 60 | end |
| 57 | 61 | ||
| 58 | def authenticate! | 62 | def authenticate! |
| @@ -129,6 +133,18 @@ module API | @@ -129,6 +133,18 @@ module API | ||
| 129 | 133 | ||
| 130 | private | 134 | private |
| 131 | 135 | ||
| 136 | + def add_pagination_headers(paginated, per_page) | ||
| 137 | + request_url = request.url.split('?').first | ||
| 138 | + | ||
| 139 | + links = [] | ||
| 140 | + links << %(<#{request_url}?page=#{paginated.current_page - 1}&per_page=#{per_page}>; rel="prev") unless paginated.first_page? | ||
| 141 | + links << %(<#{request_url}?page=#{paginated.current_page + 1}&per_page=#{per_page}>; rel="next") unless paginated.last_page? | ||
| 142 | + links << %(<#{request_url}?page=1&per_page=#{per_page}>; rel="first") | ||
| 143 | + links << %(<#{request_url}?page=#{paginated.total_pages}&per_page=#{per_page}>; rel="last") | ||
| 144 | + | ||
| 145 | + header 'Link', links.join(', ') | ||
| 146 | + end | ||
| 147 | + | ||
| 132 | def abilities | 148 | def abilities |
| 133 | @abilities ||= begin | 149 | @abilities ||= begin |
| 134 | abilities = Six.new | 150 | abilities = Six.new |
spec/requests/api/issues_spec.rb
| @@ -25,6 +25,12 @@ describe API::API do | @@ -25,6 +25,12 @@ describe API::API do | ||
| 25 | json_response.should be_an Array | 25 | json_response.should be_an Array |
| 26 | json_response.first['title'].should == issue.title | 26 | json_response.first['title'].should == issue.title |
| 27 | end | 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 | end | 34 | end |
| 29 | end | 35 | end |
| 30 | 36 |