]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/remove.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / api_crud / src / community / remove.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   build_response::build_community_response,
5   community::{CommunityResponse, RemoveCommunity},
6   context::LemmyContext,
7   utils::{is_admin, local_user_view_from_jwt},
8 };
9 use lemmy_db_schema::{
10   source::{
11     community::{Community, CommunityUpdateForm},
12     moderator::{ModRemoveCommunity, ModRemoveCommunityForm},
13   },
14   traits::Crud,
15 };
16 use lemmy_utils::{
17   error::{LemmyError, LemmyErrorExt, LemmyErrorType},
18   utils::time::naive_from_unix,
19 };
20
21 #[async_trait::async_trait(?Send)]
22 impl PerformCrud for RemoveCommunity {
23   type Response = CommunityResponse;
24
25   #[tracing::instrument(skip(context))]
26   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommunityResponse, LemmyError> {
27     let data: &RemoveCommunity = self;
28     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
29
30     // Verify its an admin (only an admin can remove a community)
31     is_admin(&local_user_view)?;
32
33     // Do the remove
34     let community_id = data.community_id;
35     let removed = data.removed;
36     Community::update(
37       &mut context.pool(),
38       community_id,
39       &CommunityUpdateForm::builder()
40         .removed(Some(removed))
41         .build(),
42     )
43     .await
44     .with_lemmy_type(LemmyErrorType::CouldntUpdateCommunity)?;
45
46     // Mod tables
47     let expires = data.expires.map(naive_from_unix);
48     let form = ModRemoveCommunityForm {
49       mod_person_id: local_user_view.person.id,
50       community_id: data.community_id,
51       removed: Some(removed),
52       reason: data.reason.clone(),
53       expires,
54     };
55     ModRemoveCommunity::create(&mut context.pool(), &form).await?;
56
57     build_community_response(context, local_user_view, community_id).await
58   }
59 }