From 49d7b4bc122daee042105e9101a073da7287e052 Mon Sep 17 00:00:00 2001 From: Antonio Scandurra Date: Mon, 13 Jun 2022 17:30:01 +0200 Subject: [PATCH] Allow specifying `query`, `limit` and `page` when hitting `/api/users` This is needed to introduce pagination and search in our admin panel. --- crates/collab/src/api.rs | 21 +++++++++++++++++++-- crates/collab/src/db.rs | 14 +++++++++----- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/collab/src/api.rs b/crates/collab/src/api.rs index 86db1d28d0..9ef834a1e2 100644 --- a/crates/collab/src/api.rs +++ b/crates/collab/src/api.rs @@ -70,8 +70,25 @@ pub async fn validate_api_token(req: Request, next: Next) -> impl IntoR Ok::<_, Error>(next.run(req).await) } -async fn get_users(Extension(app): Extension>) -> Result>> { - let users = app.db.get_all_users().await?; +#[derive(Debug, Deserialize)] +struct GetUsersQueryParams { + query: Option, + page: Option, + limit: Option, +} + +async fn get_users( + Query(params): Query, + Extension(app): Extension>, +) -> Result>> { + let limit = params.limit.unwrap_or(100); + let users = if let Some(query) = params.query { + app.db.fuzzy_search_users(&query, limit).await? + } else { + app.db + .get_all_users(params.page.unwrap_or(0), limit) + .await? + }; Ok(Json(users)) } diff --git a/crates/collab/src/db.rs b/crates/collab/src/db.rs index fc8c3f8d3e..4326e21f0e 100644 --- a/crates/collab/src/db.rs +++ b/crates/collab/src/db.rs @@ -17,7 +17,7 @@ pub trait Db: Send + Sync { email_address: Option<&str>, admin: bool, ) -> Result; - async fn get_all_users(&self) -> Result>; + async fn get_all_users(&self, page: u32, limit: u32) -> Result>; async fn fuzzy_search_users(&self, query: &str, limit: u32) -> Result>; async fn get_user_by_id(&self, id: UserId) -> Result>; async fn get_users_by_ids(&self, ids: Vec) -> Result>; @@ -141,9 +141,13 @@ impl Db for PostgresDb { .map(UserId)?) } - async fn get_all_users(&self) -> Result> { - let query = "SELECT * FROM users ORDER BY github_login ASC"; - Ok(sqlx::query_as(query).fetch_all(&self.pool).await?) + async fn get_all_users(&self, page: u32, limit: u32) -> Result> { + let query = "SELECT * FROM users ORDER BY github_login ASC LIMIT $1 OFFSET $2"; + Ok(sqlx::query_as(query) + .bind(limit) + .bind(page * limit) + .fetch_all(&self.pool) + .await?) } async fn fuzzy_search_users(&self, name_query: &str, limit: u32) -> Result> { @@ -1665,7 +1669,7 @@ pub mod tests { } } - async fn get_all_users(&self) -> Result> { + async fn get_all_users(&self, _page: u32, _limit: u32) -> Result> { unimplemented!() }