Merge pull request #708 from AppFlowy-IO/reaction-endpoint-bugfix

fix: reaction endpoint bugfix
This commit is contained in:
Khor Shu Heng 2024-07-29 18:57:01 +08:00 committed by GitHub
commit 928781d01e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 151 additions and 156 deletions

View File

@ -1,40 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n avr.comment_id,\n avr.reaction_type,\n au.uuid AS user_uuid,\n au.name AS user_name\n FROM af_published_view_reaction avr\n INNER JOIN af_user au ON avr.created_by = au.uid\n WHERE view_id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "comment_id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "reaction_type",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "user_uuid",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "user_name",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "304da1f7fec4fcd69c2e0e0bbb24edb0bce2e988c6fea1eb856b7625b4d1f16f"
}

View File

@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n avr.reaction_type,\n MIN(avr.created_at) AS reaction_type_creation_at,\n ARRAY_AGG((au.uuid, au.name)) AS \"users!: Vec<AFWebUserRow>\"\n FROM af_published_view_reaction avr\n INNER JOIN af_user au ON avr.created_by = au.uid\n WHERE comment_id = $1\n GROUP BY reaction_type\n ORDER BY reaction_type_creation_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "reaction_type",
"type_info": "Text"
},
{
"ordinal": 1,
"name": "reaction_type_creation_at",
"type_info": "Timestamptz"
},
{
"ordinal": 2,
"name": "users!: Vec<AFWebUserRow>",
"type_info": "RecordArray"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
null,
null
]
},
"hash": "74eaa9170bfd355ec23bfaf793e091e2b1433ddb59ec9f5fa811a914c38d71a7"
}

View File

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "\n DELETE FROM af_published_view_reaction\n WHERE view_id = $1 AND created_by = (SELECT uid FROM af_user WHERE uuid = $2) AND reaction_type = $3\n ", "query": "\n DELETE FROM af_published_view_reaction\n WHERE comment_id = $1 AND created_by = (SELECT uid FROM af_user WHERE uuid = $2) AND reaction_type = $3\n ",
"describe": { "describe": {
"columns": [], "columns": [],
"parameters": { "parameters": {
@ -12,5 +12,5 @@
}, },
"nullable": [] "nullable": []
}, },
"hash": "3bf9811b3cfc16b677c76acee21342b892cf815954e4516589493aae01555dc0" "hash": "816a026ca4c25329b2fb24d59efde9ab71798ff8b31ce7320e02344d4e8b3e42"
} }

View File

@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n avr.comment_id,\n avr.reaction_type,\n MIN(avr.created_at) AS reaction_type_creation_at,\n ARRAY_AGG((au.uuid, au.name)) AS \"users!: Vec<AFWebUserRow>\"\n FROM af_published_view_reaction avr\n INNER JOIN af_user au ON avr.created_by = au.uid\n WHERE view_id = $1\n GROUP BY comment_id, reaction_type\n ORDER BY reaction_type_creation_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "comment_id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "reaction_type",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "reaction_type_creation_at",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "users!: Vec<AFWebUserRow>",
"type_info": "RecordArray"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false,
null,
null
]
},
"hash": "9d6cdb956061b5cbd2198ab5215508c2ea58a462e8decbc4804e45335c3770f8"
}

View File

@ -1,40 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n avr.comment_id,\n avr.reaction_type,\n au.uuid AS user_uuid,\n au.name AS user_name\n FROM af_published_view_reaction avr\n INNER JOIN af_user au ON avr.created_by = au.uid\n WHERE comment_id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "comment_id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "reaction_type",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "user_uuid",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "user_name",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "f9a80c40a2dea06b391a065c946472ff8e1a8e63425155e88b472b91c1e24f3a"
}

View File

@ -111,8 +111,8 @@ impl Client {
pub async fn create_reaction_on_comment( pub async fn create_reaction_on_comment(
&self, &self,
reaction_type: &str, reaction_type: &str,
comment_id: &uuid::Uuid,
view_id: &uuid::Uuid, view_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
) -> Result<(), AppResponseError> { ) -> Result<(), AppResponseError> {
let url = format!( let url = format!(
"{}/api/workspace/published-info/{}/reaction", "{}/api/workspace/published-info/{}/reaction",

View File

@ -851,7 +851,7 @@ pub struct GlobalComments {
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AFWebUser { pub struct AFWebUser {
pub uid: Uuid, pub uuid: Uuid,
pub name: String, pub name: String,
pub avatar_url: Option<String>, pub avatar_url: Option<String>,
} }

View File

@ -3,6 +3,7 @@ use database_entity::dto::{
GlobalComment, PublishCollabItem, PublishInfo, Reaction, GlobalComment, PublishCollabItem, PublishInfo, Reaction,
}; };
use futures_util::stream::BoxStream; use futures_util::stream::BoxStream;
use serde::Serialize;
use sqlx::{types::uuid, Executor, PgPool, Postgres, Transaction}; use sqlx::{types::uuid, Executor, PgPool, Postgres, Transaction};
use std::{collections::HashMap, ops::DerefMut}; use std::{collections::HashMap, ops::DerefMut};
use tracing::{event, instrument}; use tracing::{event, instrument};
@ -1149,7 +1150,7 @@ pub async fn select_comments_for_published_view_orderd_by_recency<
.iter() .iter()
.map(|row| { .map(|row| {
let comment_creator = row.user_uuid.map(|uuid| AFWebUser { let comment_creator = row.user_uuid.map(|uuid| AFWebUser {
uid: uuid, uuid,
name: row name: row
.user_name .user_name
.as_ref() .as_ref()
@ -1228,13 +1229,16 @@ pub async fn update_comment_deletion_status<'a, E: Executor<'a, Database = Postg
Ok(()) Ok(())
} }
#[derive(PartialEq, Eq, Hash)] #[derive(sqlx::Type, Serialize, Debug)]
struct ReactionKey { struct AFWebUserRow {
comment_id: Uuid, uuid: Uuid,
reaction_type: String, name: String,
} }
pub async fn select_reactions_for_published_view<'a, E: Executor<'a, Database = Postgres>>( pub async fn select_reactions_for_published_view_ordered_by_reaction_type_creation_time<
'a,
E: Executor<'a, Database = Postgres>,
>(
executor: E, executor: E,
view_id: &Uuid, view_id: &Uuid,
) -> Result<Vec<Reaction>, AppError> { ) -> Result<Vec<Reaction>, AppError> {
@ -1243,89 +1247,76 @@ pub async fn select_reactions_for_published_view<'a, E: Executor<'a, Database =
SELECT SELECT
avr.comment_id, avr.comment_id,
avr.reaction_type, avr.reaction_type,
au.uuid AS user_uuid, MIN(avr.created_at) AS reaction_type_creation_at,
au.name AS user_name ARRAY_AGG((au.uuid, au.name)) AS "users!: Vec<AFWebUserRow>"
FROM af_published_view_reaction avr FROM af_published_view_reaction avr
INNER JOIN af_user au ON avr.created_by = au.uid INNER JOIN af_user au ON avr.created_by = au.uid
WHERE view_id = $1 WHERE view_id = $1
GROUP BY comment_id, reaction_type
ORDER BY reaction_type_creation_at
"#, "#,
view_id, view_id,
) )
.fetch_all(executor) .fetch_all(executor)
.await?; .await?;
let reaction_to_users_map: HashMap<ReactionKey, Vec<AFWebUser>> = rows.iter().fold(
HashMap::new(), let reactions = rows
|mut acc: HashMap<ReactionKey, Vec<AFWebUser>>, row| {
let users = acc
.entry(ReactionKey {
comment_id: row.comment_id,
reaction_type: row.reaction_type.clone(),
})
.or_default();
users.push(AFWebUser {
uid: row.user_uuid,
name: row.user_name.clone(),
avatar_url: None,
});
acc
},
);
let reactions = reaction_to_users_map
.iter() .iter()
.map( .map(|r| Reaction {
|( reaction_type: r.reaction_type.clone(),
ReactionKey { react_users: r
comment_id, .users
reaction_type, .iter()
}, .map(|u| AFWebUser {
users, uuid: u.uuid,
)| Reaction { name: u.name.clone(),
comment_id: *comment_id, avatar_url: None,
reaction_type: reaction_type.clone(), })
react_users: users.clone(), .collect(),
}, comment_id: r.comment_id,
) })
.collect(); .collect();
Ok(reactions) Ok(reactions)
} }
pub async fn select_reactions_for_comment<'a, E: Executor<'a, Database = Postgres>>( pub async fn select_reactions_for_comment_ordered_by_reaction_type_creation_time<
'a,
E: Executor<'a, Database = Postgres>,
>(
executor: E, executor: E,
comment_id: &Uuid, comment_id: &Uuid,
) -> Result<Vec<Reaction>, AppError> { ) -> Result<Vec<Reaction>, AppError> {
let rows = sqlx::query!( let rows = sqlx::query!(
r#" r#"
SELECT SELECT
avr.comment_id,
avr.reaction_type, avr.reaction_type,
au.uuid AS user_uuid, MIN(avr.created_at) AS reaction_type_creation_at,
au.name AS user_name ARRAY_AGG((au.uuid, au.name)) AS "users!: Vec<AFWebUserRow>"
FROM af_published_view_reaction avr FROM af_published_view_reaction avr
INNER JOIN af_user au ON avr.created_by = au.uid INNER JOIN af_user au ON avr.created_by = au.uid
WHERE comment_id = $1 WHERE comment_id = $1
GROUP BY reaction_type
ORDER BY reaction_type_creation_at
"#, "#,
comment_id, comment_id,
) )
.fetch_all(executor) .fetch_all(executor)
.await?; .await?;
let reaction_type_to_users_map: HashMap<String, Vec<AFWebUser>> = rows.iter().fold(
HashMap::new(), let reactions = rows
|mut acc: HashMap<String, Vec<AFWebUser>>, row| {
let users = acc.entry(row.reaction_type.clone()).or_default();
users.push(AFWebUser {
uid: row.user_uuid,
name: row.user_name.clone(),
avatar_url: None,
});
acc
},
);
let reactions = reaction_type_to_users_map
.iter() .iter()
.map(|(reaction_type, users)| Reaction { .map(|r| Reaction {
reaction_type: reaction_type.clone(), reaction_type: r.reaction_type.clone(),
react_users: users.clone(), react_users: r
.users
.iter()
.map(|u| AFWebUser {
uuid: u.uuid,
name: u.name.clone(),
avatar_url: None,
})
.collect(),
comment_id: *comment_id, comment_id: *comment_id,
}) })
.collect(); .collect();
@ -1365,24 +1356,24 @@ pub async fn insert_reaction_on_comment<'a, E: Executor<'a, Database = Postgres>
pub async fn delete_reaction_from_comment<'a, E: Executor<'a, Database = Postgres>>( pub async fn delete_reaction_from_comment<'a, E: Executor<'a, Database = Postgres>>(
executor: E, executor: E,
view_id: &Uuid, comment_id: &Uuid,
user_uuid: &Uuid, user_uuid: &Uuid,
reaction_type: &str, reaction_type: &str,
) -> Result<(), AppError> { ) -> Result<(), AppError> {
let res = sqlx::query!( let res = sqlx::query!(
r#" r#"
DELETE FROM af_published_view_reaction DELETE FROM af_published_view_reaction
WHERE view_id = $1 AND created_by = (SELECT uid FROM af_user WHERE uuid = $2) AND reaction_type = $3 WHERE comment_id = $1 AND created_by = (SELECT uid FROM af_user WHERE uuid = $2) AND reaction_type = $3
"#, "#,
view_id, comment_id,
user_uuid, user_uuid,
reaction_type, reaction_type,
).execute(executor).await?; ).execute(executor).await?;
if res.rows_affected() != 1 { if res.rows_affected() != 1 {
tracing::error!( tracing::error!(
"Failed to delete reaction from published view, view_id: {}, user_id: {}, reaction_type: {}, rows_affected: {}", "Failed to delete reaction from published comment, comment_id: {}, user_id: {}, reaction_type: {}, rows_affected: {}",
view_id, user_uuid, reaction_type, res.rows_affected() comment_id, user_uuid, reaction_type, res.rows_affected()
); );
}; };

View File

@ -0,0 +1 @@
ALTER TABLE af_published_view_reaction ADD COLUMN created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP;

View File

@ -198,8 +198,14 @@ pub async fn get_reactions_on_published_view(
comment_id: &Option<Uuid>, comment_id: &Option<Uuid>,
) -> Result<Vec<Reaction>, AppError> { ) -> Result<Vec<Reaction>, AppError> {
let reaction = match comment_id { let reaction = match comment_id {
Some(comment_id) => select_reactions_for_comment(pg_pool, comment_id).await?, Some(comment_id) => {
None => select_reactions_for_published_view(pg_pool, view_id).await?, select_reactions_for_comment_ordered_by_reaction_type_creation_time(pg_pool, comment_id)
.await?
},
None => {
select_reactions_for_published_view_ordered_by_reaction_type_creation_time(pg_pool, view_id)
.await?
},
}; };
Ok(reaction) Ok(reaction)
} }

View File

@ -454,23 +454,24 @@ async fn test_publish_reactions() {
let like_emoji = "👍"; let like_emoji = "👍";
let party_emoji = "🎉"; let party_emoji = "🎉";
page_owner_client page_owner_client
.create_reaction_on_comment(like_emoji, &likable_comment_id, &view_id) .create_reaction_on_comment(like_emoji, &view_id, &likable_comment_id)
.await .await
.unwrap(); .unwrap();
let guest_client = localhost_client(); let guest_client = localhost_client();
let result = guest_client let result = guest_client
.create_reaction_on_comment(like_emoji, &likable_comment_id, &view_id) .create_reaction_on_comment(like_emoji, &view_id, &likable_comment_id)
.await; .await;
assert!(result.is_err()); assert!(result.is_err());
assert_eq!(result.unwrap_err().code, ErrorCode::NotLoggedIn); assert_eq!(result.unwrap_err().code, ErrorCode::NotLoggedIn);
let (user_client, _) = generate_unique_registered_user_client().await; let (user_client, _) = generate_unique_registered_user_client().await;
sleep(Duration::from_millis(1));
user_client user_client
.create_reaction_on_comment(like_emoji, &likable_comment_id, &view_id) .create_reaction_on_comment(party_emoji, &view_id, &party_comment_id)
.await .await
.unwrap(); .unwrap();
user_client user_client
.create_reaction_on_comment(party_emoji, &party_comment_id, &view_id) .create_reaction_on_comment(like_emoji, &view_id, &likable_comment_id)
.await .await
.unwrap(); .unwrap();
@ -479,6 +480,8 @@ async fn test_publish_reactions() {
.await .await
.unwrap() .unwrap()
.reactions; .reactions;
assert_eq!(reactions[0].reaction_type, like_emoji);
assert_eq!(reactions[1].reaction_type, party_emoji);
let reaction_count: HashMap<String, i32> = reactions let reaction_count: HashMap<String, i32> = reactions
.iter() .iter()
.map(|r| (r.reaction_type.clone(), r.react_users.len() as i32)) .map(|r| (r.reaction_type.clone(), r.react_users.len() as i32))
@ -489,12 +492,12 @@ async fn test_publish_reactions() {
// Test if the reactions are deleted correctly based on view and comment id // Test if the reactions are deleted correctly based on view and comment id
let result = guest_client let result = guest_client
.delete_reaction_on_comment(like_emoji, &likable_comment_id, &view_id) .delete_reaction_on_comment(like_emoji, &view_id, &likable_comment_id)
.await; .await;
assert!(result.is_err()); assert!(result.is_err());
assert_eq!(result.unwrap_err().code, ErrorCode::NotLoggedIn); assert_eq!(result.unwrap_err().code, ErrorCode::NotLoggedIn);
user_client user_client
.delete_reaction_on_comment(like_emoji, &likable_comment_id, &view_id) .delete_reaction_on_comment(like_emoji, &view_id, &likable_comment_id)
.await .await
.unwrap(); .unwrap();