2024-09-27 23:17:33 -04:00
use crate ::routes ::comments ::{ Comment , CommentInputPayload };
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
}
pub async fn insert_comment (
pool : & Pool < Postgres > ,
comment_input : CommentInputPayload ,
) -> Result < Comment , sqlx ::Error > {
sqlx ::query! ( "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 )
. fetch_one ( pool )
. await
}
2024-09-24 20:26:15 -04:00
}