From 5a43e5e38bea77d63074a8db9a319e3ff77fd75a Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Sat, 10 Sep 2022 11:11:35 +0200 Subject: Add pagination --- src/models/model.rs | 20 ++++++++++++++++++-- src/models/user.rs | 19 +++++++++++++++++-- 2 files changed, 35 insertions(+), 4 deletions(-) (limited to 'src/models') diff --git a/src/models/model.rs b/src/models/model.rs index e3fc7ac..a87cddb 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -1,4 +1,6 @@ +use crate::config::PAGE_LIMIT; use crate::db::get_client; + use crate::errors::AppError; use sqlx::types::JsonValue; @@ -111,18 +113,32 @@ impl Model { } /// List all models - pub async fn list() -> Result, AppError> { + pub async fn list(page: i64) -> Result, AppError> { let pool = unsafe { get_client() }; let rows = sqlx::query_as!( ModelUser, r#"SELECT models.*, json_build_object('id', users.id, 'email', users.email, 'username', users.username, 'is_staff', users.is_staff) as author - FROM models JOIN users ON users.id = models.author_id"# + FROM models JOIN users ON users.id = models.author_id + LIMIT $1 OFFSET $2 + "#, + PAGE_LIMIT, + PAGE_LIMIT * page ) .fetch_all(pool) .await?; Ok(rows) } + + /// Return the number of models. + pub async fn count() -> Result { + let pool = unsafe { get_client() }; + let row = sqlx::query!(r#"SELECT COUNT(id) as count FROM models"#) + .fetch_one(pool) + .await?; + + Ok(row.count.unwrap()) + } } diff --git a/src/models/user.rs b/src/models/user.rs index 71b35b6..22bd130 100644 --- a/src/models/user.rs +++ b/src/models/user.rs @@ -1,3 +1,4 @@ +use crate::config::PAGE_LIMIT; use crate::db::get_client; use crate::errors::AppError; @@ -113,15 +114,29 @@ impl User { } /// List all users - pub async fn list() -> Result, AppError> { + pub async fn list(page: i64) -> Result, AppError> { let pool = unsafe { get_client() }; let rows = sqlx::query_as!( UserList, - r#"SELECT id, email, username, is_staff FROM users"# + r#"SELECT id, email, username, is_staff FROM users + LIMIT $1 OFFSET $2 + "#, + PAGE_LIMIT, + PAGE_LIMIT * page ) .fetch_all(pool) .await?; Ok(rows) } + + /// Return the number of users. + pub async fn count() -> Result { + let pool = unsafe { get_client() }; + let row = sqlx::query!(r#"SELECT COUNT(id) as count FROM users"#) + .fetch_one(pool) + .await?; + + Ok(row.count.unwrap()) + } } -- cgit v1.2.3-71-g8e6c