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