92 lines
2.5 KiB
Rust
92 lines
2.5 KiB
Rust
use core::fmt;
|
|
use serde::Serialize;
|
|
use tracing::instrument;
|
|
|
|
use crate::database::Database;
|
|
use crate::types::http::{ResponseCode, Result};
|
|
|
|
use super::comment::Comment;
|
|
|
|
#[derive(Serialize)]
|
|
pub struct Post {
|
|
pub post_id: u64,
|
|
pub user_id: u64,
|
|
pub content: String,
|
|
pub date: u64,
|
|
pub likes: u64,
|
|
pub liked: bool,
|
|
pub comments: Vec<Comment>,
|
|
}
|
|
|
|
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(skip(db))]
|
|
pub fn from_post_id(db: &Database, self_id: u64, post_id: u64) -> Result<Self> {
|
|
let Ok(Some(mut post)) = db.get_post(post_id) else {
|
|
return Err(ResponseCode::BadRequest.text("Post does not exist"))
|
|
};
|
|
|
|
let liked = db.get_liked(self_id, post.post_id).unwrap_or(false);
|
|
post.liked = liked;
|
|
|
|
Ok(post)
|
|
}
|
|
|
|
#[instrument(skip(db))]
|
|
pub fn from_post_page(db: &Database, self_id: u64, page: u64) -> Result<Vec<Self>> {
|
|
let Ok(mut posts) = db.get_post_page(page) else {
|
|
return Err(ResponseCode::BadRequest.text("Failed to fetch posts"))
|
|
};
|
|
|
|
for post in &mut posts {
|
|
let liked = db.get_liked(self_id, post.post_id).unwrap_or(false);
|
|
post.liked = liked;
|
|
}
|
|
|
|
Ok(posts)
|
|
}
|
|
|
|
#[instrument(skip(db))]
|
|
pub fn from_user_post_page(
|
|
db: &Database,
|
|
self_id: u64,
|
|
user_id: u64,
|
|
page: u64,
|
|
) -> Result<Vec<Self>> {
|
|
let Ok(mut posts) = db.get_users_post_page(user_id, page) else {
|
|
return Err(ResponseCode::BadRequest.text("Failed to fetch posts"))
|
|
};
|
|
|
|
for post in &mut posts {
|
|
let liked = db.get_liked(self_id, post.post_id).unwrap_or(false);
|
|
post.liked = liked;
|
|
}
|
|
|
|
Ok(posts)
|
|
}
|
|
|
|
#[instrument(skip(db))]
|
|
pub fn reterieve_all(db: &Database) -> Result<Vec<Self>> {
|
|
let Ok(posts) = db.get_all_posts() else {
|
|
return Err(ResponseCode::InternalServerError.text("Failed to fetch posts"))
|
|
};
|
|
Ok(posts)
|
|
}
|
|
|
|
#[instrument(skip(db))]
|
|
pub fn new(db: &Database, user_id: u64, content: String) -> Result<Self> {
|
|
let Ok(post) = db.add_post(user_id, &content) else {
|
|
tracing::error!("Failed to create post");
|
|
return Err(ResponseCode::InternalServerError.text("Failed to create post"))
|
|
};
|
|
|
|
Ok(post)
|
|
}
|
|
}
|