]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_block_view.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / db_views_actor / src / community_block_view.rs
1 use crate::structs::CommunityBlockView;
2 use diesel::{result::Error, ExpressionMethods, QueryDsl};
3 use diesel_async::RunQueryDsl;
4 use lemmy_db_schema::{
5   newtypes::PersonId,
6   schema::{community, community_block, 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 CommunityBlockViewTuple = (PersonSafe, CommunitySafe);
16
17 impl CommunityBlockView {
18   pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result<Vec<Self>, Error> {
19     let conn = &mut get_conn(pool).await?;
20     let res = community_block::table
21       .inner_join(person::table)
22       .inner_join(community::table)
23       .select((
24         Person::safe_columns_tuple(),
25         Community::safe_columns_tuple(),
26       ))
27       .filter(community_block::person_id.eq(person_id))
28       .filter(community::deleted.eq(false))
29       .filter(community::removed.eq(false))
30       .order_by(community_block::published)
31       .load::<CommunityBlockViewTuple>(conn)
32       .await?;
33
34     Ok(Self::from_tuple_to_vec(res))
35   }
36 }
37
38 impl ViewToVec for CommunityBlockView {
39   type DbTuple = CommunityBlockViewTuple;
40   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
41     items
42       .into_iter()
43       .map(|a| Self {
44         person: a.0,
45         community: a.1,
46       })
47       .collect::<Vec<Self>>()
48   }
49 }