]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/person_block.rs
9cd275563219ea0da788eb46f9ba5f27eb0526fb
[lemmy.git] / crates / db_schema / src / impls / person_block.rs
1 use crate::{
2   newtypes::PersonId,
3   schema::person_block::dsl::{person_block, person_id, target_id},
4   source::person_block::{PersonBlock, PersonBlockForm},
5   traits::Blockable,
6   utils::{get_conn, DbPool},
7 };
8 use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
9 use diesel_async::RunQueryDsl;
10
11 impl PersonBlock {
12   pub async fn read(
13     pool: &DbPool,
14     for_person_id: PersonId,
15     for_recipient_id: PersonId,
16   ) -> Result<Self, Error> {
17     let conn = &mut get_conn(pool).await?;
18     person_block
19       .filter(person_id.eq(for_person_id))
20       .filter(target_id.eq(for_recipient_id))
21       .first::<Self>(conn)
22       .await
23   }
24 }
25
26 #[async_trait]
27 impl Blockable for PersonBlock {
28   type Form = PersonBlockForm;
29   async fn block(pool: &DbPool, person_block_form: &PersonBlockForm) -> Result<Self, Error> {
30     let conn = &mut get_conn(pool).await?;
31     insert_into(person_block)
32       .values(person_block_form)
33       .on_conflict((person_id, target_id))
34       .do_update()
35       .set(person_block_form)
36       .get_result::<Self>(conn)
37       .await
38   }
39   async fn unblock(pool: &DbPool, person_block_form: &Self::Form) -> Result<usize, Error> {
40     let conn = &mut get_conn(pool).await?;
41     diesel::delete(
42       person_block
43         .filter(person_id.eq(person_block_form.person_id))
44         .filter(target_id.eq(person_block_form.target_id)),
45     )
46     .execute(conn)
47     .await
48   }
49 }