From 233ea7c41628094bc7f3f1652246a117fa79ef1a Mon Sep 17 00:00:00 2001 From: Lucien Cartier-Tilet Date: Wed, 18 Jan 2023 11:21:34 +0100 Subject: [PATCH] =?UTF-8?q?Add=20method=20to=20get=20user=E2=80=99s=20foll?= =?UTF-8?q?owers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/models/users.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/db/models/users.rs b/src/db/models/users.rs index 956a0df..9cac0eb 100644 --- a/src/db/models/users.rs +++ b/src/db/models/users.rs @@ -64,7 +64,46 @@ impl User { None } } + }) + .collect::>()) + } + #[graphql(description = "Who follows this user")] + pub fn followers(&self, context: &Context) -> FieldResult> { + use schema::userfollows::dsl; + let conn = &mut context.db.conn().map_err(|e| { + DatabaseError::new( + format!("Failed to connect to database: {e:?}"), + "Database connection error", + ) + })?; + Ok(dsl::userfollows + .filter(dsl::following.eq(self.id.clone())) + .load::(conn) + .map_err(|e| { + DatabaseError::new( + format!( + "Failed to retrieve user follows from database: {e:?}" + ), + "Database reading error", + ) + })? + .iter() + .filter_map(|user_follow| { + use schema::users::dsl; + match dsl::users + .find(user_follow.follower.clone()) + .first::(conn) { + Ok(user) => Some(user), + Err(e) => { + let err = DatabaseError::new( + format!("Failed to retrieve user {} from database: {e:?}", + user_follow.follower.clone()), + "Database reading error"); + debug!("{}", err); + None + } + } }) .collect::>()) }