]> Untitled Git - lemmy.git/blob - crates/api/src/comment/distinguish.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / api / src / comment / distinguish.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentResponse, DistinguishComment},
5   context::LemmyContext,
6   utils::{check_community_ban, is_mod_or_admin, local_user_view_from_jwt},
7 };
8 use lemmy_db_schema::{
9   source::comment::{Comment, CommentUpdateForm},
10   traits::Crud,
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 DistinguishComment {
17   type Response = CommentResponse;
18
19   #[tracing::instrument(skip(context))]
20   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommentResponse, LemmyError> {
21     let data: &DistinguishComment = self;
22     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
23
24     let comment_id = data.comment_id;
25     let orig_comment = CommentView::read(&mut context.pool(), comment_id, None).await?;
26
27     check_community_ban(
28       local_user_view.person.id,
29       orig_comment.community.id,
30       &mut context.pool(),
31     )
32     .await?;
33
34     // Verify that only a mod or admin can distinguish a comment
35     is_mod_or_admin(
36       &mut context.pool(),
37       local_user_view.person.id,
38       orig_comment.community.id,
39     )
40     .await?;
41
42     // Update the Comment
43     let comment_id = data.comment_id;
44     let form = CommentUpdateForm::builder()
45       .distinguished(Some(data.distinguished))
46       .build();
47     Comment::update(&mut context.pool(), comment_id, &form)
48       .await
49       .with_lemmy_type(LemmyErrorType::CouldntUpdateComment)?;
50
51     let comment_id = data.comment_id;
52     let person_id = local_user_view.person.id;
53     let comment_view = CommentView::read(&mut context.pool(), comment_id, Some(person_id)).await?;
54
55     Ok(CommentResponse {
56       comment_view,
57       recipient_ids: Vec::new(),
58       form_id: None,
59     })
60   }
61 }