2025-07-07 21:05:27 -04:00
use crate ::{
routes ::comments ::{ Comment , CommentInputPayload },
utils ::pagination ::Pagination ,
};
2024-09-27 23:17:33 -04:00
use sqlx ::{ Pool , Postgres };
2024-09-24 20:26:15 -04:00
2024-09-22 22:38:35 -04:00
pub struct CommentsDatasource ;
2024-09-24 20:26:15 -04:00
impl CommentsDatasource {
2024-09-27 23:17:33 -04:00
pub async fn get_posts_comments (
pool : & Pool < Postgres > ,
post_id : i32 ,
) -> Result < Vec < Comment > , sqlx ::Error > {
sqlx ::query_as! ( Comment , "SELECT c.comment_id, c.name, c.body, c.created_at FROM comments c LEFT JOIN posts p ON p.post_id = c.post_id WHERE p.post_id = $1 AND c.deleted_at IS NULL ORDER BY created_at DESC LIMIT 20" , post_id )
. fetch_all ( pool )
. await
}
2024-09-28 01:48:58 -04:00
2024-09-27 23:17:33 -04:00
pub async fn insert_comment (
pool : & Pool < Postgres > ,
comment_input : CommentInputPayload ,
) -> Result < Comment , sqlx ::Error > {
2024-09-28 01:48:58 -04:00
sqlx ::query_as! ( Comment , "INSERT INTO comments (post_id, name, body) VALUES ($1, $2, $3) RETURNING comment_id, name, body, created_at" , comment_input . post_id , comment_input . name , comment_input . body )
2024-09-27 23:17:33 -04:00
. fetch_one ( pool )
. await
}
2024-09-28 01:48:58 -04:00
pub async fn get_index_comments (
pool : & Pool < Postgres > ,
pagination : Pagination ,
) -> Result < Vec < Comment > , sqlx ::Error > {
2025-07-07 21:05:27 -04:00
let offset : i64 = ( pagination . page - 1 ) * pagination . limit ;
sqlx ::query_as! ( Comment , "SELECT comment_id, name, body, created_at FROM comments ORDER BY created_at DESC LIMIT $1 OFFSET $2" , pagination . page , offset )
2024-09-28 01:48:58 -04:00
. fetch_all ( pool )
. await
}
2024-09-24 20:26:15 -04:00
}