]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_hide_community_view.rs
10397076cc7d3aa8ef9e261ee5ac3190ada6d3f1
[lemmy.git] / crates / db_views_moderator / src / mod_hide_community_view.rs
1 use crate::structs::ModHideCommunityView;
2 use diesel::{result::Error, *};
3 use lemmy_db_schema::{
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   utils::limit_and_offset,
13 };
14
15 type ModHideCommunityViewTuple = (ModHideCommunity, PersonSafe, CommunitySafe);
16
17 impl ModHideCommunityView {
18   // Pass in mod_id as admin_id because only admins can do this action
19   pub fn list(
20     conn: &PgConnection,
21     community_id: Option<CommunityId>,
22     admin_id: Option<PersonId>,
23     page: Option<i64>,
24     limit: Option<i64>,
25   ) -> Result<Vec<Self>, Error> {
26     let mut query = mod_hide_community::table
27       .inner_join(person::table)
28       .inner_join(community::table.on(mod_hide_community::community_id.eq(community::id)))
29       .select((
30         mod_hide_community::all_columns,
31         Person::safe_columns_tuple(),
32         Community::safe_columns_tuple(),
33       ))
34       .into_boxed();
35
36     if let Some(community_id) = community_id {
37       query = query.filter(mod_hide_community::community_id.eq(community_id));
38     };
39
40     if let Some(admin_id) = admin_id {
41       query = query.filter(mod_hide_community::mod_person_id.eq(admin_id));
42     };
43
44     let (limit, offset) = limit_and_offset(page, limit)?;
45
46     let res = query
47       .limit(limit)
48       .offset(offset)
49       .order_by(mod_hide_community::when_.desc())
50       .load::<ModHideCommunityViewTuple>(conn)?;
51
52     Ok(Self::from_tuple_to_vec(res))
53   }
54 }
55
56 impl ViewToVec for ModHideCommunityView {
57   type DbTuple = ModHideCommunityViewTuple;
58   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
59     items
60       .into_iter()
61       .map(|a| Self {
62         mod_hide_community: a.0,
63         admin: a.1,
64         community: a.2,
65       })
66       .collect::<Vec<Self>>()
67   }
68 }