use crate::{ models::comments::{Comment, CommentInputPayload}, utils::pagination::Pagination, }; use sqlx::{Pool, Postgres}; pub struct CommentsDatasource; impl CommentsDatasource { pub async fn get_posts_comments( pool: &Pool, post_id: i32, ) -> Result, 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, comment_input: CommentInputPayload, ) -> Result { 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) .fetch_one(pool) .await } pub async fn get_index_comments( pool: &Pool, pagination: Pagination, ) -> Result, sqlx::Error> { 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) .fetch_all(pool) .await } }