added pagination to a given authors page

This commit is contained in:
2025-07-07 21:05:27 -04:00
parent a64b8fdceb
commit 6694f47d70
16 changed files with 350 additions and 93 deletions

View File

@@ -1,6 +1,9 @@
use sqlx::{Pool, Postgres};
use crate::routes::{authors::Author, comments::Pagination, posts::Post};
use crate::{
routes::{authors::Author, posts::Post},
utils::pagination::Pagination,
};
pub struct AuthorsDatasource;
impl AuthorsDatasource {
@@ -8,11 +11,11 @@ impl AuthorsDatasource {
pool: &Pool<Postgres>,
pagination: Pagination,
) -> Result<Vec<Author>, sqlx::Error> {
let offset: i64 = (pagination.page_number - 1) * pagination.page_size;
let offset: i64 = (pagination.page - 1) * pagination.limit;
sqlx::query_as!(
Author,
"SELECT author_id, first_name, last_name, bio, image FROM authors ORDER BY created_at DESC LIMIT $1 OFFSET $2",
pagination.page_size,
pagination.page,
offset,
)
.fetch_all(pool)
@@ -32,13 +35,32 @@ impl AuthorsDatasource {
pub async fn get_authors_posts(
pool: &Pool<Postgres>,
author_id: i32,
) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as!(
Post,
"SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.created_at, a.author_id FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.author_id = $1 ORDER BY created_at DESC",
pagination: Pagination,
) -> Result<(Vec<Post>, i64), sqlx::Error> {
let offset: i64 = (pagination.page - 1) * pagination.limit;
println!(
"Author ID: {}, Page: {}, Size: {}, Offset: {}",
author_id, pagination.page, pagination.limit, offset
);
let total_count = sqlx::query_scalar!(
"SELECT COUNT(*) FROM posts p WHERE p.deleted_at IS NULL AND p.author_id = $1",
author_id
)
.fetch_one(pool)
.await?
.unwrap_or(0);
let posts_query = sqlx::query_as!(
Post,
"SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.created_at, a.author_id FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.author_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
author_id,
pagination.limit,
offset,
)
.fetch_all(pool)
.await
.await?;
Ok((posts_query, total_count))
}
}