2024-09-28 01:48:58 -04:00
use sqlx ::{ Pool , Postgres };
2025-07-07 21:05:27 -04:00
use crate ::{
2026-11-09 00:04:22 -05:00
models ::{ authors ::Author , posts ::Post },
2025-07-07 21:05:27 -04:00
utils ::pagination ::Pagination ,
};
2024-09-28 01:48:58 -04:00
2024-09-22 22:38:35 -04:00
pub struct AuthorsDatasource ;
2024-09-28 01:48:58 -04:00
impl AuthorsDatasource {
pub async fn get_all (
pool : & Pool < Postgres > ,
pagination : Pagination ,
) -> Result < Vec < Author > , sqlx ::Error > {
2025-07-07 21:05:27 -04:00
let offset : i64 = ( pagination . page - 1 ) * pagination . limit ;
2024-09-28 01:48:58 -04:00
sqlx ::query_as! (
Author ,
2024-12-02 18:29:23 -05:00
"SELECT author_id, first_name, last_name, bio, image FROM authors ORDER BY created_at DESC LIMIT $1 OFFSET $2" ,
2025-07-07 21:05:27 -04:00
pagination . page ,
2024-09-28 01:48:58 -04:00
offset ,
)
. fetch_all ( pool )
. await
}
pub async fn get_one ( pool : & Pool < Postgres > , author_id : i32 ) -> Result < Author , sqlx ::Error > {
sqlx ::query_as! (
Author ,
2024-12-02 18:29:23 -05:00
"SELECT author_id, first_name, last_name, bio, image FROM authors WHERE author_id = $1" ,
2024-09-28 01:48:58 -04:00
author_id
)
. fetch_one ( pool )
. await
}
2024-09-28 02:26:17 -04:00
pub async fn get_authors_posts (
pool : & Pool < Postgres > ,
author_id : i32 ,
2025-07-07 21:05:27 -04:00
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" ,
2024-09-28 02:26:17 -04:00
author_id
)
2025-07-07 21:05:27 -04:00
. fetch_one ( pool )
. await ?
. unwrap_or ( 0 );
let posts_query = sqlx ::query_as! (
Post ,
2026-11-09 00:04:22 -05:00
"SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.body_gemtext, p.created_at, p.publish_date, 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" ,
2025-07-07 21:05:27 -04:00
author_id ,
pagination . limit ,
offset ,
)
2024-09-28 02:26:17 -04:00
. fetch_all ( pool )
2025-07-07 21:05:27 -04:00
. await ? ;
Ok (( posts_query , total_count ))
2024-09-28 02:26:17 -04:00
}
2024-09-28 01:48:58 -04:00
}