]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_remove_post_view.rs
Merge branch 'split_user_table' into strictly_type_db_ids
[lemmy.git] / crates / db_views_moderator / src / mod_remove_post_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_post, person, post},
5   source::{
6     community::{Community, CommunitySafe},
7     moderator::ModRemovePost,
8     person::{Person, PersonSafe},
9     post::Post,
10   },
11   CommunityId,
12   PersonId,
13 };
14 use serde::Serialize;
15
16 #[derive(Debug, Serialize, Clone)]
17 pub struct ModRemovePostView {
18   pub mod_remove_post: ModRemovePost,
19   pub moderator: PersonSafe,
20   pub post: Post,
21   pub community: CommunitySafe,
22 }
23
24 type ModRemovePostViewTuple = (ModRemovePost, PersonSafe, Post, CommunitySafe);
25
26 impl ModRemovePostView {
27   pub fn list(
28     conn: &PgConnection,
29     community_id: Option<CommunityId>,
30     mod_person_id: Option<PersonId>,
31     page: Option<i64>,
32     limit: Option<i64>,
33   ) -> Result<Vec<Self>, Error> {
34     let mut query = mod_remove_post::table
35       .inner_join(person::table)
36       .inner_join(post::table)
37       .inner_join(community::table.on(post::community_id.eq(community::id)))
38       .select((
39         mod_remove_post::all_columns,
40         Person::safe_columns_tuple(),
41         post::all_columns,
42         Community::safe_columns_tuple(),
43       ))
44       .into_boxed();
45
46     if let Some(community_id) = community_id {
47       query = query.filter(post::community_id.eq(community_id));
48     };
49
50     if let Some(mod_person_id) = mod_person_id {
51       query = query.filter(mod_remove_post::mod_person_id.eq(mod_person_id));
52     };
53
54     let (limit, offset) = limit_and_offset(page, limit);
55
56     let res = query
57       .limit(limit)
58       .offset(offset)
59       .order_by(mod_remove_post::when_.desc())
60       .load::<ModRemovePostViewTuple>(conn)?;
61
62     Ok(Self::from_tuple_to_vec(res))
63   }
64 }
65
66 impl ViewToVec for ModRemovePostView {
67   type DbTuple = ModRemovePostViewTuple;
68   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
69     items
70       .iter()
71       .map(|a| Self {
72         mod_remove_post: a.0.to_owned(),
73         moderator: a.1.to_owned(),
74         post: a.2.to_owned(),
75         community: a.3.to_owned(),
76       })
77       .collect::<Vec<Self>>()
78   }
79 }