]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/list.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / api_crud / src / community / list.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{ListCommunities, ListCommunitiesResponse},
5   utils::{check_private_instance, get_local_user_view_from_jwt_opt},
6 };
7 use lemmy_db_schema::{source::local_site::LocalSite, traits::DeleteableOrRemoveable};
8 use lemmy_db_views_actor::community_view::CommunityQuery;
9 use lemmy_utils::{error::LemmyError, ConnectionId};
10 use lemmy_websocket::LemmyContext;
11
12 #[async_trait::async_trait(?Send)]
13 impl PerformCrud for ListCommunities {
14   type Response = ListCommunitiesResponse;
15
16   #[tracing::instrument(skip(context, _websocket_id))]
17   async fn perform(
18     &self,
19     context: &Data<LemmyContext>,
20     _websocket_id: Option<ConnectionId>,
21   ) -> Result<ListCommunitiesResponse, LemmyError> {
22     let data: &ListCommunities = self;
23     let local_user_view =
24       get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
25         .await?;
26     let local_site = LocalSite::read(context.pool()).await?;
27
28     check_private_instance(&local_user_view, &local_site)?;
29
30     let person_id = local_user_view.to_owned().map(|l| l.person.id);
31
32     let sort = data.sort;
33     let listing_type = data.type_;
34     let page = data.page;
35     let limit = data.limit;
36     let local_user = local_user_view.map(|l| l.local_user);
37     let mut communities = CommunityQuery::builder()
38       .pool(context.pool())
39       .listing_type(listing_type)
40       .sort(sort)
41       .local_user(local_user.as_ref())
42       .page(page)
43       .limit(limit)
44       .build()
45       .list()
46       .await?;
47
48     // Blank out deleted or removed info for non-logged in users
49     if person_id.is_none() {
50       for cv in communities
51         .iter_mut()
52         .filter(|cv| cv.community.deleted || cv.community.removed)
53       {
54         cv.community = cv.to_owned().community.blank_out_deleted_or_removed_info();
55       }
56     }
57
58     // Return the jwt
59     Ok(ListCommunitiesResponse { communities })
60   }
61 }