]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_follower_view.rs
7fbbcf8511e2fa3a1f830275f5e1e9cda82b260a
[lemmy.git] / crates / db_views_actor / src / community_follower_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_schema::{
3   newtypes::{CommunityId, PersonId},
4   schema::{community, community_follower, person},
5   source::{
6     community::{Community, CommunitySafe},
7     person::{Person, PersonSafe},
8   },
9   traits::{ToSafe, ViewToVec},
10 };
11 use serde::{Deserialize, Serialize};
12
13 #[derive(Debug, Serialize, Deserialize, Clone)]
14 pub struct CommunityFollowerView {
15   pub community: CommunitySafe,
16   pub follower: PersonSafe,
17 }
18
19 type CommunityFollowerViewTuple = (CommunitySafe, PersonSafe);
20
21 impl CommunityFollowerView {
22   pub fn for_community(conn: &PgConnection, community_id: CommunityId) -> Result<Vec<Self>, Error> {
23     let res = community_follower::table
24       .inner_join(community::table)
25       .inner_join(person::table)
26       .select((
27         Community::safe_columns_tuple(),
28         Person::safe_columns_tuple(),
29       ))
30       .filter(community_follower::community_id.eq(community_id))
31       .load::<CommunityFollowerViewTuple>(conn)?;
32
33     Ok(Self::from_tuple_to_vec(res))
34   }
35
36   pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> {
37     let res = community_follower::table
38       .inner_join(community::table)
39       .inner_join(person::table)
40       .select((
41         Community::safe_columns_tuple(),
42         Person::safe_columns_tuple(),
43       ))
44       .filter(community_follower::person_id.eq(person_id))
45       .load::<CommunityFollowerViewTuple>(conn)?;
46
47     Ok(Self::from_tuple_to_vec(res))
48   }
49 }
50
51 impl ViewToVec for CommunityFollowerView {
52   type DbTuple = CommunityFollowerViewTuple;
53   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
54     items
55       .iter()
56       .map(|a| Self {
57         community: a.0.to_owned(),
58         follower: a.1.to_owned(),
59       })
60       .collect::<Vec<Self>>()
61   }
62 }