]> Untitled Git - lemmy.git/blob - crates/api/src/comment/save.rs
Split apart api files (#2216)
[lemmy.git] / crates / api / src / comment / save.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   comment::{CommentResponse, SaveComment},
6   get_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::comment_view::CommentView;
13 use lemmy_utils::{ConnectionId, LemmyError};
14 use lemmy_websocket::LemmyContext;
15
16 #[async_trait::async_trait(?Send)]
17 impl Perform for SaveComment {
18   type Response = CommentResponse;
19
20   #[tracing::instrument(skip(context, _websocket_id))]
21   async fn perform(
22     &self,
23     context: &Data<LemmyContext>,
24     _websocket_id: Option<ConnectionId>,
25   ) -> Result<CommentResponse, LemmyError> {
26     let data: &SaveComment = self;
27     let local_user_view =
28       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
29
30     let comment_saved_form = CommentSavedForm {
31       comment_id: data.comment_id,
32       person_id: local_user_view.person.id,
33     };
34
35     if data.save {
36       let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form);
37       blocking(context.pool(), save_comment)
38         .await?
39         .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?;
40     } else {
41       let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form);
42       blocking(context.pool(), unsave_comment)
43         .await?
44         .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?;
45     }
46
47     let comment_id = data.comment_id;
48     let person_id = local_user_view.person.id;
49     let comment_view = blocking(context.pool(), move |conn| {
50       CommentView::read(conn, comment_id, Some(person_id))
51     })
52     .await??;
53
54     Ok(CommentResponse {
55       comment_view,
56       recipient_ids: Vec::new(),
57       form_id: None,
58     })
59   }
60 }