From 4faaaf244d953188f6ee8e67eee67b98d1314f3b Mon Sep 17 00:00:00 2001 From: Lucien Cartier-Tilet Date: Wed, 18 Jan 2023 11:12:57 +0100 Subject: [PATCH] Clarify GraphQL following methods on user Remove `following` and replace it with `usersFollowed` and `languagesFollowed` --- src/db/models/languages.rs | 6 ++--- src/db/models/users.rs | 50 +++++++++++++++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/db/models/languages.rs b/src/db/models/languages.rs index 2a74018..c93b5b7 100644 --- a/src/db/models/languages.rs +++ b/src/db/models/languages.rs @@ -293,7 +293,7 @@ pub struct LangTranslatesTo { #[derive(Queryable, Insertable, Debug, Clone, PartialEq, Eq)] #[diesel(table_name = userfollowlanguage)] pub struct UserFollowLanguage { - id: i32, - lang: Uuid, - userid: String, + pub id: i32, + pub lang: Uuid, + pub userid: String, } diff --git a/src/db/models/users.rs b/src/db/models/users.rs index 976c1e4..956a0df 100644 --- a/src/db/models/users.rs +++ b/src/db/models/users.rs @@ -1,10 +1,11 @@ use super::{ super::schema, + languages::{Language, UserFollowLanguage}, words::{Word, WordLearning, WordLearningStatus}, }; use diesel::prelude::*; use juniper::FieldResult; -use tracing::{debug, info}; +use tracing::{debug, info, warn}; use schema::{userfollows, users}; @@ -29,8 +30,8 @@ impl User { } #[graphql(description = "Who the user follows")] - pub fn following(&self, context: &Context) -> FieldResult> { - use super::super::schema::{userfollows, users}; + pub fn users_followed(&self, context: &Context) -> FieldResult> { + use schema::{userfollows, users}; let conn = &mut context.db.conn().map_err(|e| { DatabaseError::new( format!("Failed to connect to database: {e:?}"), @@ -68,6 +69,49 @@ impl User { .collect::>()) } + #[graphql(description = "Which languages the user follows")] + pub fn languages_followed( + &self, + context: &Context, + ) -> FieldResult> { + use schema::userfollowlanguage::dsl; + let conn = &mut context.db.conn().map_err(|e| { + DatabaseError::new( + format!("Failed to connect to database: {e:?}"), + "Database connection error", + ) + })?; + Ok(dsl::userfollowlanguage + .filter(dsl::userid.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(|lang_follow| { + use schema::languages::dsl; + match dsl::languages + .find(lang_follow.lang) + .first::(conn) { + Ok(language) => Some(language), + Err(e) => { + warn!( + "Failed to retrieve language {} from database: {e:?}", + lang_follow.lang + ); + None + } + } + }) + .collect::>() + ) + } + #[graphql( description = "What words the user is learning or has learned", arguments(status(