feat: add has_next and has_prev to paginated posts response
Clients no longer need to compute page boundaries themselves; the API now returns boolean flags indicating whether more pages exist in each direction. Includes tests for first, middle, and last page.
This commit is contained in:
@@ -101,10 +101,13 @@ module Volumen
|
|||||||
page = positive_int(params["page"], 1)
|
page = positive_int(params["page"], 1)
|
||||||
limit = positive_int(params["limit"], 20).clamp(1, 100)
|
limit = positive_int(params["limit"], 20).clamp(1, 100)
|
||||||
offset = (page - 1) * limit
|
offset = (page - 1) * limit
|
||||||
|
total = posts.length
|
||||||
{
|
{
|
||||||
"page" => page,
|
"page" => page,
|
||||||
"page_size" => limit,
|
"page_size" => limit,
|
||||||
"total" => posts.length,
|
"total" => total,
|
||||||
|
"has_next" => offset + limit < total,
|
||||||
|
"has_prev" => page > 1,
|
||||||
"posts" => posts[offset, limit].to_a.map(&:summary)
|
"posts" => posts[offset, limit].to_a.map(&:summary)
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -274,4 +274,31 @@ class ServerTest < Minitest::Test
|
|||||||
data = JSON.parse(last_response.body)
|
data = JSON.parse(last_response.body)
|
||||||
assert_equal 1, data["total"]
|
assert_equal 1, data["total"]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_pagination_has_next_and_prev
|
||||||
|
# Create enough posts to paginate
|
||||||
|
5.times do |i|
|
||||||
|
File.write(File.join(@dir, "post-#{i}.md"), <<~POST)
|
||||||
|
+++
|
||||||
|
title = "Post #{i}"
|
||||||
|
+++
|
||||||
|
|
||||||
|
Body #{i}.
|
||||||
|
POST
|
||||||
|
end
|
||||||
|
get "/api/volumen/posts?page=1&limit=2"
|
||||||
|
data = JSON.parse(last_response.body)
|
||||||
|
assert_equal true, data["has_next"]
|
||||||
|
assert_equal false, data["has_prev"]
|
||||||
|
|
||||||
|
get "/api/volumen/posts?page=2&limit=2"
|
||||||
|
data = JSON.parse(last_response.body)
|
||||||
|
assert_equal true, data["has_next"]
|
||||||
|
assert_equal true, data["has_prev"]
|
||||||
|
|
||||||
|
get "/api/volumen/posts?page=3&limit=2"
|
||||||
|
data = JSON.parse(last_response.body)
|
||||||
|
assert_equal false, data["has_next"]
|
||||||
|
assert_equal true, data["has_prev"]
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user