summaryrefslogtreecommitdiff
path: root/src/types/comment.rs
blob: 0836950bb46bc2b704a3d7e8a5fbbee1b46094b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use serde::Serialize;
use tracing::instrument;

use crate::{
    database::Database,
    types::http::{ResponseCode, Result},
};

#[derive(Serialize)]
pub struct Comment {
    pub comment_id: u64,
    pub user_id: u64,
    pub post_id: u64,
    pub date: u64,
    pub content: String,
}

impl Comment {
    #[instrument(skip(db))]
    pub fn new(db: &Database, user_id: u64, post_id: u64, content: &str) -> Result<Self> {
        let Ok(comment) = db.add_comment(user_id, post_id, content) else {
            tracing::error!("Failed to create comment");
            return Err(ResponseCode::InternalServerError.text("Failed to create post")) 
        };

        Ok(comment)
    }

    #[instrument(skip(db))]
    pub fn from_comment_page(db: &Database, page: u64, post_id: u64) -> Result<Vec<Self>> {
        let Ok(posts) = db.get_comments_page(page, post_id) else {
            return Err(ResponseCode::BadRequest.text("Failed to fetch comments"))
        };
        Ok(posts)
    }

    #[instrument(skip(db))]
    pub fn reterieve_all(db: &Database) -> Result<Vec<Self>> {
        let Ok(posts) = db.get_all_comments() else {
            return Err(ResponseCode::InternalServerError.text("Failed to fetch comments"))
        };
        Ok(posts)
    }
}