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