From 0ec69adbe2f035cccccfcdfc623c6a151a0c45e6 Mon Sep 17 00:00:00 2001 From: silverpill Date: Wed, 1 Dec 2021 14:46:09 +0000 Subject: [PATCH] Refactor favourite/unfavourite API methods to make fewer DB queries --- src/mastodon_api/statuses/views.rs | 14 ++++++++------ src/models/posts/queries.rs | 1 + 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/mastodon_api/statuses/views.rs b/src/mastodon_api/statuses/views.rs index 7f2cb3a..30009f7 100644 --- a/src/mastodon_api/statuses/views.rs +++ b/src/mastodon_api/statuses/views.rs @@ -176,18 +176,20 @@ async fn favourite( ) -> Result { let db_client = &mut **get_database_client(&db_pool).await?; let current_user = get_current_user(db_client, auth.token()).await?; - let post = get_post_by_id(db_client, &status_id).await?; + let mut post = get_post_by_id(db_client, &status_id).await?; if !can_view_post(Some(¤t_user), &post) { return Err(HttpError::NotFoundError("post")); }; let reaction_created = match create_reaction( db_client, ¤t_user.id, &status_id, ).await { - Ok(_) => true, + Ok(_) => { + post.reaction_count += 1; + true + }, Err(DatabaseError::AlreadyExists(_)) => false, // post already favourited Err(other_error) => return Err(other_error.into()), }; - let mut post = get_post_by_id(db_client, &status_id).await?; get_reposted_posts(db_client, vec![&mut post]).await?; get_actions_for_posts(db_client, ¤t_user.id, vec![&mut post]).await?; @@ -219,15 +221,15 @@ async fn unfavourite( ) -> Result { let db_client = &mut **get_database_client(&db_pool).await?; let current_user = get_current_user(db_client, auth.token()).await?; - let post = get_post_by_id(db_client, &status_id).await?; + let mut post = get_post_by_id(db_client, &status_id).await?; if !can_view_post(Some(¤t_user), &post) { return Err(HttpError::NotFoundError("post")); }; match delete_reaction(db_client, ¤t_user.id, &status_id).await { + Ok(_) => post.reaction_count -= 1, Err(DatabaseError::NotFound(_)) => (), // post not favourited - other_result => other_result?, + Err(other_error) => return Err(other_error.into()), } - let mut post = get_post_by_id(db_client, &status_id).await?; get_reposted_posts(db_client, vec![&mut post]).await?; get_actions_for_posts(db_client, ¤t_user.id, vec![&mut post]).await?; let status = Status::from_post(post, &config.instance_url()); diff --git a/src/models/posts/queries.rs b/src/models/posts/queries.rs index 761740d..190ffe5 100644 --- a/src/models/posts/queries.rs +++ b/src/models/posts/queries.rs @@ -323,6 +323,7 @@ pub async fn get_thread( post_id: &Uuid, current_user_id: Option<&Uuid>, ) -> Result, DatabaseError> { + // Exclude direct messages let mut condition = format!( "post.visibility = {visibility_public}", visibility_public=i16::from(&Visibility::Public),