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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
use core::fmt;
use serde::Serialize;
use std::collections::HashSet;
use tracing::instrument;
use crate::database;
use crate::types::http::{ResponseCode, Result};
#[derive(Serialize)]
pub struct Post {
pub post_id: u64,
pub user_id: u64,
pub content: String,
pub likes: HashSet<u64>,
pub comments: Vec<(u64, String)>,
pub date: u64,
}
impl fmt::Debug for Post {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Post")
.field("post_id", &self.post_id)
.finish()
}
}
impl Post {
#[instrument()]
pub fn from_post_id(post_id: u64) -> Result<Self> {
let Ok(Some(post)) = database::posts::get_post(post_id) else {
return Err(ResponseCode::BadRequest.text("Post does not exist"))
};
Ok(post)
}
#[instrument()]
pub fn from_post_page(page: u64) -> Result<Vec<Self>> {
let Ok(posts) = database::posts::get_post_page(page) else {
return Err(ResponseCode::BadRequest.text("Failed to fetch posts"))
};
Ok(posts)
}
#[instrument()]
pub fn from_user_id(user_id: u64) -> Result<Vec<Self>> {
let Ok(posts) = database::posts::get_users_posts(user_id) else {
return Err(ResponseCode::BadRequest.text("Failed to fetch posts"))
};
Ok(posts)
}
#[instrument()]
pub fn new(user_id: u64, content: String) -> Result<Self> {
let Ok(post) = database::posts::add_post(user_id, &content) else {
tracing::error!("Failed to create post");
return Err(ResponseCode::InternalServerError.text("Failed to create post"))
};
Ok(post)
}
#[instrument()]
pub fn comment(&mut self, user_id: u64, content: String) -> Result<()> {
self.comments.push((user_id, content));
if database::posts::update_post(self.post_id, &self.likes, &self.comments).is_err() {
tracing::error!("Failed to comment on post");
return Err(ResponseCode::InternalServerError.text("Failed to comment on post"));
}
Ok(())
}
#[instrument()]
pub fn like(&mut self, user_id: u64, state: bool) -> Result<()> {
if state {
self.likes.insert(user_id);
} else {
self.likes.remove(&user_id);
}
if database::posts::update_post(self.post_id, &self.likes, &self.comments).is_err() {
tracing::error!("Failed to change like state on post");
return Err(
ResponseCode::InternalServerError.text("Failed to change like state on post")
);
}
Ok(())
}
}
|