From 1dcd61fa341ba101018b7fea202a8d1e565ee082 Mon Sep 17 00:00:00 2001 From: Jared Reisinger Date: Fri, 12 May 2017 13:28:35 -0700 Subject: [PATCH] Add pagination to /admin/users/list API Prior to this, only the first 100 active/new/etc. users were available via the `/admin/users/list` API. This change adds support for a `page=#` querystring parameter so that *all* of the users can be retrieved. Requests for pages past the last user result in an empty-list response; requests for negative pages (or zero) just return the first page. Added tests to cover pagination. --- lib/admin_user_index_query.rb | 6 ++++- .../components/admin_user_index_query_spec.rb | 24 ++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/admin_user_index_query.rb b/lib/admin_user_index_query.rb index 8279ad20170..ffd1dd404d4 100644 --- a/lib/admin_user_index_query.rb +++ b/lib/admin_user_index_query.rb @@ -25,7 +25,11 @@ class AdminUserIndexQuery } def find_users(limit=100) - find_users_query.limit(limit) + page = params[:page].to_i - 1 + if page < 0 + page = 0 + end + find_users_query.limit(limit).offset(page * limit) end def count_users diff --git a/spec/components/admin_user_index_query_spec.rb b/spec/components/admin_user_index_query_spec.rb index e5c71957084..cb0bf161308 100644 --- a/spec/components/admin_user_index_query_spec.rb +++ b/spec/components/admin_user_index_query_spec.rb @@ -26,7 +26,7 @@ describe AdminUserIndexQuery do query = ::AdminUserIndexQuery.new({ order: "trust_level" }) expect(query.find_users_query.to_sql).to match("trust_level DESC") end - + it "allows custom ordering asc" do query = ::AdminUserIndexQuery.new({ order: "trust_level", ascending: true }) expect(query.find_users_query.to_sql).to match("trust_level ASC" ) @@ -43,6 +43,28 @@ describe AdminUserIndexQuery do end end + describe "pagination" do + it "defaults to the first page" do + query = ::AdminUserIndexQuery.new({}) + expect(query.find_users.to_sql).to match("OFFSET 0") + end + + it "offsets by 100 by default for page 2" do + query = ::AdminUserIndexQuery.new({ page: "2"}) + expect(query.find_users.to_sql).to match("OFFSET 100") + end + + it "offsets by limit for page 2" do + query = ::AdminUserIndexQuery.new({ page: "2"}) + expect(query.find_users(10).to_sql).to match("OFFSET 10") + end + + it "ignores negative pages" do + query = ::AdminUserIndexQuery.new({ page: "-2" }) + expect(query.find_users.to_sql).to match("OFFSET 0") + end + end + describe "no users with trust level" do TrustLevel.levels.each do |key, value|