diff options
author | Tyler Murphy <tylermurphy534@gmail.com> | 2023-01-26 17:29:16 -0500 |
---|---|---|
committer | Tyler Murphy <tylermurphy534@gmail.com> | 2023-01-26 17:29:16 -0500 |
commit | 88209d88236c3d865a9f5174a0dced31920859bf (patch) | |
tree | 89a9985927393005cf632950b585a6a227b1c679 /src/types/post.rs | |
download | xssbook-88209d88236c3d865a9f5174a0dced31920859bf.tar.gz xssbook-88209d88236c3d865a9f5174a0dced31920859bf.tar.bz2 xssbook-88209d88236c3d865a9f5174a0dced31920859bf.zip |
i did things
Diffstat (limited to 'src/types/post.rs')
-rw-r--r-- | src/types/post.rs | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/src/types/post.rs b/src/types/post.rs new file mode 100644 index 0000000..94f0a9e --- /dev/null +++ b/src/types/post.rs @@ -0,0 +1,83 @@ +use std::collections::HashSet; +use serde::Serialize; + +use crate::database; +use crate::types::response::{Result, ResponseCode}; + +#[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 Post { + + 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.msg("Post does not exist")) + }; + + Ok(post) + } + + // pub fn from_post_ids(post_ids: Vec<u64>) -> Vec<Self> { + // post_ids.iter().map(|id| { + // let Ok(post) = Post::from_post_id(*id) else { + // return None; + // }; + // Some(post) + // }).flatten().collect() + // } + + pub fn from_post_page(page: u64) -> Result<Vec<Self>> { + let Ok(posts) = database::posts::get_post_page(page) else { + return Err(ResponseCode::BadRequest.msg("Failed to fetch posts")) + }; + Ok(posts) + } + + 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.msg("Failed to fetch posts")) + }; + Ok(posts) + } + + pub fn new(user_id: u64, content: String) -> Result<Self> { + let Ok(post) = database::posts::add_post(user_id, &content) else { + return Err(ResponseCode::InternalServerError.msg("Failed to create post")) + }; + + Ok(post) + } + + 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() { + return Err(ResponseCode::InternalServerError.msg("Failed to comment on post")) + } + + Ok(()) + } + + 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() { + return Err(ResponseCode::InternalServerError.msg("Failed to comment on post")) + } + + Ok(()) + } + +}
\ No newline at end of file |