Files
mtusi2026lab3/src/Messenger.Api/Data/Reactions.cs
T

49 lines
2.3 KiB
C#

using Npgsql;
namespace Messenger.Api.Data;
public sealed record ReactionDto(Guid MessageId, string Reaction, int Count, bool Mine);
public sealed partial class AppDatabase
{
public async Task<bool> SetReactionAsync(Guid chatId, Guid messageId, Guid userId, string reaction, bool present)
{
await using var command = dataSource.CreateCommand(present ? """
WITH target AS (SELECT id FROM messages WHERE id = @message_id AND chat_id = @chat_id),
written AS (
INSERT INTO message_reactions(message_id, user_id, reaction)
SELECT id, @user_id, @reaction FROM target ON CONFLICT DO NOTHING
) SELECT EXISTS(SELECT 1 FROM target)
""" : """
WITH target AS (SELECT id FROM messages WHERE id = @message_id AND chat_id = @chat_id),
removed AS (
DELETE FROM message_reactions WHERE message_id IN (SELECT id FROM target)
AND user_id = @user_id AND reaction = @reaction
) SELECT EXISTS(SELECT 1 FROM target)
""");
command.Parameters.AddWithValue("chat_id", chatId);
command.Parameters.AddWithValue("message_id", messageId);
command.Parameters.AddWithValue("user_id", userId);
command.Parameters.AddWithValue("reaction", reaction);
return (bool)(await command.ExecuteScalarAsync())!;
}
public async Task<List<ReactionDto>> ListReactionsAsync(Guid chatId, Guid[] messageIds, Guid userId)
{
await using var command = dataSource.CreateCommand("""
SELECT r.message_id, r.reaction, count(*)::integer, bool_or(r.user_id = @user_id)
FROM message_reactions r JOIN messages m ON m.id = r.message_id
WHERE m.chat_id = @chat_id AND m.id = ANY(@message_ids)
GROUP BY r.message_id, r.reaction ORDER BY r.message_id, r.reaction
""");
command.Parameters.AddWithValue("chat_id", chatId);
command.Parameters.AddWithValue("message_ids", messageIds);
command.Parameters.AddWithValue("user_id", userId);
await using var reader = await command.ExecuteReaderAsync();
var items = new List<ReactionDto>();
while (await reader.ReadAsync())
items.Add(new(reader.GetGuid(0), reader.GetString(1), reader.GetInt32(2), reader.GetBoolean(3)));
return items;
}
}