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