]> Untitled Git - lemmy.git/blob - crates/api/src/comment/save.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / api / src / comment / save.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentResponse, SaveComment},
5   context::LemmyContext,
6   utils::local_user_view_from_jwt,
7 };
8 use lemmy_db_schema::{
9   source::comment::{CommentSaved, CommentSavedForm},
10   traits::Saveable,
11 };
12 use lemmy_db_views::structs::CommentView;
13 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
14
15 #[async_trait::async_trait(?Send)]
16 impl Perform for SaveComment {
17   type Response = CommentResponse;
18
19   #[tracing::instrument(skip(context))]
20   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommentResponse, LemmyError> {
21     let data: &SaveComment = self;
22     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
23
24     let comment_saved_form = CommentSavedForm {
25       comment_id: data.comment_id,
26       person_id: local_user_view.person.id,
27     };
28
29     if data.save {
30       CommentSaved::save(&mut context.pool(), &comment_saved_form)
31         .await
32         .with_lemmy_type(LemmyErrorType::CouldntSaveComment)?;
33     } else {
34       CommentSaved::unsave(&mut context.pool(), &comment_saved_form)
35         .await
36         .with_lemmy_type(LemmyErrorType::CouldntSaveComment)?;
37     }
38
39     let comment_id = data.comment_id;
40     let person_id = local_user_view.person.id;
41     let comment_view = CommentView::read(&mut context.pool(), comment_id, Some(person_id)).await?;
42
43     Ok(CommentResponse {
44       comment_view,
45       recipient_ids: Vec::new(),
46       form_id: None,
47     })
48   }
49 }