]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_follower_view.rs
7e37e446a774a83a84b2b95d2f0b2ecee9744c50
[lemmy.git] / crates / db_views_actor / src / community_follower_view.rs
1 use crate::structs::CommunityFollowerView;
2 use diesel::{result::Error, *};
3 use lemmy_db_schema::{
4   newtypes::{CommunityId, PersonId},
5   schema::{community, community_follower, person},
6   source::{
7     community::{Community, CommunitySafe},
8     person::{Person, PersonSafe},
9   },
10   traits::{ToSafe, ViewToVec},
11 };
12
13 type CommunityFollowerViewTuple = (CommunitySafe, PersonSafe, Option<bool>);
14
15 impl CommunityFollowerView {
16   pub fn for_community(conn: &PgConnection, community_id: CommunityId) -> Result<Vec<Self>, Error> {
17     let res = community_follower::table
18       .inner_join(community::table)
19       .inner_join(person::table)
20       .select((
21         Community::safe_columns_tuple(),
22         Person::safe_columns_tuple(),
23         community_follower::pending,
24       ))
25       .filter(community_follower::community_id.eq(community_id))
26       .order_by(community::title)
27       .load::<CommunityFollowerViewTuple>(conn)?;
28
29     Ok(Self::from_tuple_to_vec(res))
30   }
31
32   pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> {
33     let res = community_follower::table
34       .inner_join(community::table)
35       .inner_join(person::table)
36       .select((
37         Community::safe_columns_tuple(),
38         Person::safe_columns_tuple(),
39         community_follower::pending,
40       ))
41       .filter(community_follower::person_id.eq(person_id))
42       .order_by(community::title)
43       .load::<CommunityFollowerViewTuple>(conn)?;
44
45     Ok(Self::from_tuple_to_vec(res))
46   }
47
48   pub fn read(
49     conn: &PgConnection,
50     community_id: CommunityId,
51     person_id: PersonId,
52   ) -> Result<Self, Error> {
53     let (community, follower, pending) = community_follower::table
54       .inner_join(community::table)
55       .inner_join(person::table)
56       .select((
57         Community::safe_columns_tuple(),
58         Person::safe_columns_tuple(),
59         community_follower::pending,
60       ))
61       .filter(community_follower::person_id.eq(person_id))
62       .filter(community_follower::community_id.eq(community_id))
63       .first::<CommunityFollowerViewTuple>(conn)?;
64
65     Ok(Self {
66       community,
67       follower,
68       pending,
69     })
70   }
71 }
72
73 impl ViewToVec for CommunityFollowerView {
74   type DbTuple = CommunityFollowerViewTuple;
75   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
76     items
77       .iter()
78       .map(|a| Self {
79         community: a.0.to_owned(),
80         follower: a.1.to_owned(),
81         pending: a.2.to_owned(),
82       })
83       .collect::<Vec<Self>>()
84   }
85 }