]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_ban_from_community_view.rs
Merge branch 'main' into split_user_table
[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::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
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 = (
22   ModBanFromCommunity,
23   PersonSafe,
24   CommunitySafe,
25   PersonSafeAlias1,
26 );
27
28 impl ModBanFromCommunityView {
29   pub fn list(
30     conn: &PgConnection,
31     community_id: Option<i32>,
32     mod_person_id: Option<i32>,
33     page: Option<i64>,
34     limit: Option<i64>,
35   ) -> Result<Vec<Self>, Error> {
36     let mut query = mod_ban_from_community::table
37       .inner_join(person::table.on(mod_ban_from_community::mod_person_id.eq(person::id)))
38       .inner_join(community::table)
39       .inner_join(
40         person_alias_1::table.on(mod_ban_from_community::other_person_id.eq(person_alias_1::id)),
41       )
42       .select((
43         mod_ban_from_community::all_columns,
44         Person::safe_columns_tuple(),
45         Community::safe_columns_tuple(),
46         PersonAlias1::safe_columns_tuple(),
47       ))
48       .into_boxed();
49
50     if let Some(mod_person_id) = mod_person_id {
51       query = query.filter(mod_ban_from_community::mod_person_id.eq(mod_person_id));
52     };
53
54     if let Some(community_id) = community_id {
55       query = query.filter(mod_ban_from_community::community_id.eq(community_id));
56     };
57
58     let (limit, offset) = limit_and_offset(page, limit);
59
60     let res = query
61       .limit(limit)
62       .offset(offset)
63       .order_by(mod_ban_from_community::when_.desc())
64       .load::<ModBanFromCommunityViewTuple>(conn)?;
65
66     Ok(Self::from_tuple_to_vec(res))
67   }
68 }
69
70 impl ViewToVec for ModBanFromCommunityView {
71   type DbTuple = ModBanFromCommunityViewTuple;
72   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
73     items
74       .iter()
75       .map(|a| Self {
76         mod_ban_from_community: a.0.to_owned(),
77         moderator: a.1.to_owned(),
78         community: a.2.to_owned(),
79         banned_person: a.3.to_owned(),
80       })
81       .collect::<Vec<Self>>()
82   }
83 }