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