//! # Comments helper //! //! @author Pierre Hubert use crate::constants::database_tables_names::COMMENTS_TABLE; use crate::data::comment::Comment; use crate::data::error::ResultBoxError; use crate::helpers::{database, likes_helper}; use crate::helpers::likes_helper::LikeType; use crate::utils::user_data_utils::user_data_path; /// Get the comments of a post pub fn get(post_id: u64) -> ResultBoxError> { database::QueryInfo::new(COMMENTS_TABLE) .cond_u64("ID_texte", post_id) .set_order("ID") .exec(db_to_comment) } /// Turn a database entry into a comment object fn db_to_comment(row: &database::RowResult) -> ResultBoxError { Ok(Comment { id: row.get_u64("ID")?, time_sent: row.get_u64("time_insert").unwrap_or(0), user_id: row.get_user_id("ID_personne")?, post_id: row.get_u64("ID_texte")?, content: row.get_str("commentaire")?, image_path: row.get_optional_str("image_commentaire")?, }) } /// Delete a single comment pub fn delete(c: &Comment) -> ResultBoxError { // Delete associated image (if any) if let Some(image) = &c.image_path { let path = user_data_path(image.as_ref()); if path.exists() { std::fs::remove_file(&path)?; } } // Remove the likes associated with the comment likes_helper::delete_all(c.id, LikeType::COMMENT)?; // Remove the comment from the database database::DeleteQuery::new(COMMENTS_TABLE) .cond_u64("ID", c.id) .exec()?; Ok(()) } /// Delete all the comments associated to a post pub fn delete_all(post_id: u64) -> ResultBoxError { for c in &get(post_id)? { delete(c)?; } Ok(()) }