yggdrasil/api/comments/
read.rs1use crate::api::comments::types::*;
7use dioxus::prelude::*;
8
9#[server(GetComments, "/api")]
13pub async fn get_comments(post_id: i32) -> Result<CommentTreeResponse, ServerFnError> {
14 #[cfg(feature = "server")]
15 {
16 use crate::api::comments::helpers::row_to_public_comment;
17 use crate::api::error::AppError;
18 use crate::cache;
19 use crate::db::pool::get_conn;
20
21 if let Some(cached) = cache::get_comments_by_post(post_id).await {
22 let count = cached.len() as i64;
23 return Ok(CommentTreeResponse {
24 comments: cached,
25 count,
26 });
27 }
28
29 let client = get_conn().await.map_err(AppError::db_conn)?;
30
31 let rows = client
32 .query(
33 "SELECT id, parent_id, depth, author_name, author_email, author_url, content_html, created_at \
34 FROM comments \
35 WHERE post_id = $1 AND status = 'approved' AND deleted_at IS NULL \
36 AND EXISTS (SELECT 1 FROM posts p WHERE p.id = $1 AND p.status = 'published' AND p.deleted_at IS NULL) \
37 ORDER BY id ASC \
38 LIMIT 200",
39 &[&post_id],
40 )
41 .await
42 .map_err(AppError::query)?;
43
44 let comments: Vec<_> = rows.iter().map(row_to_public_comment).collect();
45 let count = comments.len() as i64;
46
47 cache::set_comments_by_post(post_id, comments.clone()).await;
48
49 Ok(CommentTreeResponse { comments, count })
50 }
51 #[cfg(not(feature = "server"))]
52 unreachable!()
53}