]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_block_view.rs
5e24bcaabb206fbf8bd4baa6270e1b80338a4347
[lemmy.git] / crates / db_views_actor / src / community_block_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{ToSafe, ViewToVec};
3 use lemmy_db_schema::{
4   schema::{community, community_block, person},
5   source::{
6     community::{Community, CommunitySafe},
7     person::{Person, PersonSafe},
8   },
9   PersonId,
10 };
11 use serde::Serialize;
12
13 #[derive(Debug, Serialize, Clone)]
14 pub struct CommunityBlockView {
15   pub person: PersonSafe,
16   pub community: CommunitySafe,
17 }
18
19 type CommunityBlockViewTuple = (PersonSafe, CommunitySafe);
20
21 impl CommunityBlockView {
22   pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> {
23     let res = community_block::table
24       .inner_join(person::table)
25       .inner_join(community::table)
26       .select((
27         Person::safe_columns_tuple(),
28         Community::safe_columns_tuple(),
29       ))
30       .filter(community_block::person_id.eq(person_id))
31       .order_by(community_block::published)
32       .load::<CommunityBlockViewTuple>(conn)?;
33
34     Ok(Self::from_tuple_to_vec(res))
35   }
36 }
37
38 impl ViewToVec for CommunityBlockView {
39   type DbTuple = CommunityBlockViewTuple;
40   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
41     items
42       .iter()
43       .map(|a| Self {
44         person: a.0.to_owned(),
45         community: a.1.to_owned(),
46       })
47       .collect::<Vec<Self>>()
48   }
49 }