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