]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_remove_community_view.rs
Strictly typing DB id fields. Fixes #1498
[lemmy.git] / crates / db_views_moderator / src / mod_remove_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_remove_community, person},
5   source::{
6     community::{Community, CommunitySafe},
7     moderator::ModRemoveCommunity,
8     person::{Person, PersonSafe},
9   },
10   PersonId,
11 };
12 use serde::Serialize;
13
14 #[derive(Debug, Serialize, Clone)]
15 pub struct ModRemoveCommunityView {
16   pub mod_remove_community: ModRemoveCommunity,
17   pub moderator: PersonSafe,
18   pub community: CommunitySafe,
19 }
20
21 type ModRemoveCommunityTuple = (ModRemoveCommunity, PersonSafe, CommunitySafe);
22
23 impl ModRemoveCommunityView {
24   pub fn list(
25     conn: &PgConnection,
26     mod_person_id: Option<PersonId>,
27     page: Option<i64>,
28     limit: Option<i64>,
29   ) -> Result<Vec<Self>, Error> {
30     let mut query = mod_remove_community::table
31       .inner_join(person::table)
32       .inner_join(community::table)
33       .select((
34         mod_remove_community::all_columns,
35         Person::safe_columns_tuple(),
36         Community::safe_columns_tuple(),
37       ))
38       .into_boxed();
39
40     if let Some(mod_person_id) = mod_person_id {
41       query = query.filter(mod_remove_community::mod_person_id.eq(mod_person_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_remove_community::when_.desc())
50       .load::<ModRemoveCommunityTuple>(conn)?;
51
52     Ok(Self::from_tuple_to_vec(res))
53   }
54 }
55
56 impl ViewToVec for ModRemoveCommunityView {
57   type DbTuple = ModRemoveCommunityTuple;
58   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
59     items
60       .iter()
61       .map(|a| Self {
62         mod_remove_community: a.0.to_owned(),
63         moderator: a.1.to_owned(),
64         community: a.2.to_owned(),
65       })
66       .collect::<Vec<Self>>()
67   }
68 }