]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_ban_from_community_view.rs
~80% done
[lemmy.git] / crates / db_views_moderator / src / mod_ban_from_community_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{limit_and_offset, ToSafe, ViewToVec};
3 use lemmy_db_schema::{
4   schema::{community, mod_ban_from_community, person, person_alias_1},
5   source::{
6     community::{Community, CommunitySafe},
7     moderator::ModBanFromCommunity,
8     person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person},
9   },
10 };
11 use serde::Serialize;
12
13 #[derive(Debug, Serialize, Clone)]
14 pub struct ModBanFromCommunityView {
15   pub mod_ban_from_community: ModBanFromCommunity,
16   pub moderator: PersonSafe,
17   pub community: CommunitySafe,
18   pub banned_person: PersonSafeAlias1,
19 }
20
21 type ModBanFromCommunityViewTuple = (ModBanFromCommunity, PersonSafe, CommunitySafe, PersonSafeAlias1);
22
23 impl ModBanFromCommunityView {
24   pub fn list(
25     conn: &PgConnection,
26     community_id: Option<i32>,
27     mod_person_id: Option<i32>,
28     page: Option<i64>,
29     limit: Option<i64>,
30   ) -> Result<Vec<Self>, Error> {
31     let mut query = mod_ban_from_community::table
32       .inner_join(person::table.on(mod_ban_from_community::mod_person_id.eq(person::id)))
33       .inner_join(community::table)
34       .inner_join(
35         person_alias_1::table.on(mod_ban_from_community::other_person_id.eq(person_alias_1::id)),
36       )
37       .select((
38         mod_ban_from_community::all_columns,
39         Person::safe_columns_tuple(),
40         Community::safe_columns_tuple(),
41         PersonAlias1::safe_columns_tuple(),
42       ))
43       .into_boxed();
44
45     if let Some(mod_person_id) = mod_person_id {
46       query = query.filter(mod_ban_from_community::mod_person_id.eq(mod_person_id));
47     };
48
49     if let Some(community_id) = community_id {
50       query = query.filter(mod_ban_from_community::community_id.eq(community_id));
51     };
52
53     let (limit, offset) = limit_and_offset(page, limit);
54
55     let res = query
56       .limit(limit)
57       .offset(offset)
58       .order_by(mod_ban_from_community::when_.desc())
59       .load::<ModBanFromCommunityViewTuple>(conn)?;
60
61     Ok(Self::from_tuple_to_vec(res))
62   }
63 }
64
65 impl ViewToVec for ModBanFromCommunityView {
66   type DbTuple = ModBanFromCommunityViewTuple;
67   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
68     items
69       .iter()
70       .map(|a| Self {
71         mod_ban_from_community: a.0.to_owned(),
72         moderator: a.1.to_owned(),
73         community: a.2.to_owned(),
74         banned_person: a.3.to_owned(),
75       })
76       .collect::<Vec<Self>>()
77   }
78 }