]> Untitled Git - lemmy.git/blob - crates/api/src/post/feature.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / api / src / post / feature.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   build_response::build_post_response,
5   context::LemmyContext,
6   post::{FeaturePost, PostResponse},
7   utils::{
8     check_community_ban,
9     check_community_deleted_or_removed,
10     is_admin,
11     is_mod_or_admin,
12     local_user_view_from_jwt,
13   },
14 };
15 use lemmy_db_schema::{
16   source::{
17     moderator::{ModFeaturePost, ModFeaturePostForm},
18     post::{Post, PostUpdateForm},
19   },
20   traits::Crud,
21   PostFeatureType,
22 };
23 use lemmy_utils::error::LemmyError;
24
25 #[async_trait::async_trait(?Send)]
26 impl Perform for FeaturePost {
27   type Response = PostResponse;
28
29   #[tracing::instrument(skip(context))]
30   async fn perform(&self, context: &Data<LemmyContext>) -> Result<PostResponse, LemmyError> {
31     let data: &FeaturePost = self;
32     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
33
34     let post_id = data.post_id;
35     let orig_post = Post::read(&mut context.pool(), post_id).await?;
36
37     check_community_ban(
38       local_user_view.person.id,
39       orig_post.community_id,
40       &mut context.pool(),
41     )
42     .await?;
43     check_community_deleted_or_removed(orig_post.community_id, &mut context.pool()).await?;
44
45     if data.feature_type == PostFeatureType::Community {
46       // Verify that only the mods can feature in community
47       is_mod_or_admin(
48         &mut context.pool(),
49         local_user_view.person.id,
50         orig_post.community_id,
51       )
52       .await?;
53     } else {
54       is_admin(&local_user_view)?;
55     }
56
57     // Update the post
58     let post_id = data.post_id;
59     let new_post: PostUpdateForm = if data.feature_type == PostFeatureType::Community {
60       PostUpdateForm::builder()
61         .featured_community(Some(data.featured))
62         .build()
63     } else {
64       PostUpdateForm::builder()
65         .featured_local(Some(data.featured))
66         .build()
67     };
68     Post::update(&mut context.pool(), post_id, &new_post).await?;
69
70     // Mod tables
71     let form = ModFeaturePostForm {
72       mod_person_id: local_user_view.person.id,
73       post_id: data.post_id,
74       featured: data.featured,
75       is_featured_community: data.feature_type == PostFeatureType::Community,
76     };
77
78     ModFeaturePost::create(&mut context.pool(), &form).await?;
79
80     build_post_response(
81       context,
82       orig_post.community_id,
83       local_user_view.person.id,
84       post_id,
85     )
86     .await
87   }
88 }