]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_follower_view.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / db_views_actor / src / community_follower_view.rs
1 use crate::structs::CommunityFollowerView;
2 use diesel::{result::Error, ExpressionMethods, QueryDsl};
3 use diesel_async::RunQueryDsl;
4 use lemmy_db_schema::{
5   newtypes::{CommunityId, PersonId},
6   schema::{community, community_follower, person},
7   source::{
8     community::{Community, CommunitySafe},
9     person::{Person, PersonSafe},
10   },
11   traits::{ToSafe, ViewToVec},
12   utils::{get_conn, DbPool},
13 };
14
15 type CommunityFollowerViewTuple = (CommunitySafe, PersonSafe);
16
17 impl CommunityFollowerView {
18   pub async fn for_community(pool: &DbPool, community_id: CommunityId) -> Result<Vec<Self>, Error> {
19     let conn = &mut get_conn(pool).await?;
20     let res = community_follower::table
21       .inner_join(community::table)
22       .inner_join(person::table)
23       .select((
24         Community::safe_columns_tuple(),
25         Person::safe_columns_tuple(),
26       ))
27       .filter(community_follower::community_id.eq(community_id))
28       .order_by(community::title)
29       .load::<CommunityFollowerViewTuple>(conn)
30       .await?;
31
32     Ok(Self::from_tuple_to_vec(res))
33   }
34
35   pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result<Vec<Self>, Error> {
36     let conn = &mut get_conn(pool).await?;
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       .filter(community::deleted.eq(false))
46       .filter(community::removed.eq(false))
47       .order_by(community::title)
48       .load::<CommunityFollowerViewTuple>(conn)
49       .await?;
50
51     Ok(Self::from_tuple_to_vec(res))
52   }
53 }
54
55 impl ViewToVec for CommunityFollowerView {
56   type DbTuple = CommunityFollowerViewTuple;
57   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
58     items
59       .into_iter()
60       .map(|a| Self {
61         community: a.0,
62         follower: a.1,
63       })
64       .collect::<Vec<Self>>()
65   }
66 }