]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_follower_view.rs
Alpha-ordering community follows. Fixes #2062 (#2079)
[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       .order_by(community::title)
32       .load::<CommunityFollowerViewTuple>(conn)?;
33
34     Ok(Self::from_tuple_to_vec(res))
35   }
36
37   pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> {
38     let res = community_follower::table
39       .inner_join(community::table)
40       .inner_join(person::table)
41       .select((
42         Community::safe_columns_tuple(),
43         Person::safe_columns_tuple(),
44       ))
45       .filter(community_follower::person_id.eq(person_id))
46       .order_by(community::title)
47       .load::<CommunityFollowerViewTuple>(conn)?;
48
49     Ok(Self::from_tuple_to_vec(res))
50   }
51 }
52
53 impl ViewToVec for CommunityFollowerView {
54   type DbTuple = CommunityFollowerViewTuple;
55   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
56     items
57       .iter()
58       .map(|a| Self {
59         community: a.0.to_owned(),
60         follower: a.1.to_owned(),
61       })
62       .collect::<Vec<Self>>()
63   }
64 }