2024-09-28 01:48:58 -04:00
use sqlx ::{ Pool , Postgres } ;
2024-09-28 02:26:17 -04:00
use crate ::routes ::{ authors ::Author , comments ::Pagination , posts ::Post } ;
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 > {
let offset : i64 = ( pagination . page_number - 1 ) * pagination . page_size ;
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 " ,
2024-09-28 01:48:58 -04:00
pagination . page_size ,
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 ,
) -> Result < Vec < Post > , sqlx ::Error > {
sqlx ::query_as! (
Post ,
2024-12-02 18:29:23 -05:00
" 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 " ,
2024-09-28 02:26:17 -04:00
author_id
)
. fetch_all ( pool )
. await
}
2024-09-28 01:48:58 -04:00
}