]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_hide_community_view.rs
Hide community v2 (#2055)
[lemmy.git] / crates / db_views_moderator / src / mod_hide_community_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_schema::{
3   limit_and_offset,
4   newtypes::{CommunityId, PersonId},
5   schema::{community, mod_hide_community, person},
6   source::{
7     community::{Community, CommunitySafe},
8     moderator::ModHideCommunity,
9     person::{Person, PersonSafe},
10   },
11   traits::{ToSafe, ViewToVec},
12 };
13 use serde::{Deserialize, Serialize};
14
15 #[derive(Debug, Serialize, Deserialize, Clone)]
16 pub struct ModHideCommunityView {
17   pub mod_hide_community: ModHideCommunity,
18   pub admin: PersonSafe,
19   pub community: CommunitySafe,
20 }
21
22 type ModHideCommunityViewTuple = (ModHideCommunity, PersonSafe, CommunitySafe);
23
24 impl ModHideCommunityView {
25   // Pass in mod_id as admin_id because only admins can do this action
26   pub fn list(
27     conn: &PgConnection,
28     community_id: Option<CommunityId>,
29     admin_id: Option<PersonId>,
30     page: Option<i64>,
31     limit: Option<i64>,
32   ) -> Result<Vec<Self>, Error> {
33     let mut query = mod_hide_community::table
34       .inner_join(person::table)
35       .inner_join(community::table.on(mod_hide_community::community_id.eq(community::id)))
36       .select((
37         mod_hide_community::all_columns,
38         Person::safe_columns_tuple(),
39         Community::safe_columns_tuple(),
40       ))
41       .into_boxed();
42
43     if let Some(community_id) = community_id {
44       query = query.filter(mod_hide_community::community_id.eq(community_id));
45     };
46
47     if let Some(admin_id) = admin_id {
48       query = query.filter(mod_hide_community::mod_person_id.eq(admin_id));
49     };
50
51     let (limit, offset) = limit_and_offset(page, limit);
52
53     let res = query
54       .limit(limit)
55       .offset(offset)
56       .order_by(mod_hide_community::when_.desc())
57       .load::<ModHideCommunityViewTuple>(conn)?;
58
59     Ok(Self::from_tuple_to_vec(res))
60   }
61 }
62
63 impl ViewToVec for ModHideCommunityView {
64   type DbTuple = ModHideCommunityViewTuple;
65   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
66     items
67       .iter()
68       .map(|a| Self {
69         mod_hide_community: a.0.to_owned(),
70         admin: a.1.to_owned(),
71         community: a.2.to_owned(),
72       })
73       .collect::<Vec<Self>>()
74   }
75 }