Simplify code in AddReaction

This commit is contained in:
Dominic Villemure
2024-08-25 10:35:06 -04:00
parent 79c87f2091
commit c395cea0f5

View File

@@ -48,43 +48,33 @@ public class AddReaction(
{ {
var content = await context.Contents.SingleAsync(x => x.Id == req.ContentId, ct); var content = await context.Contents.SingleAsync(x => x.Id == req.ContentId, ct);
var reactionEnum = req.Reaction.ToEnum<Reaction>(); var reactionEnum = req.Reaction.ToEnum<Reaction>();
var currentReaction = content.Reactions.SingleOrDefault(x => x.UserId == req.UserId);
var hasReacted = content.Reactions.Any(x => x.UserId == req.UserId); // Already reacted or reaction didn't change, do nothing
if (currentReaction != null && currentReaction.Reaction == reactionEnum)
if (hasReacted)
{ {
var currentReaction = content.Reactions.Single(x => x.UserId == req.UserId); return;
if (currentReaction.Reaction == reactionEnum) return;
if (reactionEnum.HasValue)
{
content.Reactions.Remove(currentReaction);
var reaction = new ContentReaction
{
Reaction = reactionEnum.Value,
UserId = req.UserId,
UserName = req.UserName
};
content.Reactions.Add(reaction);
}
} }
else
// User has already reacted, remove the existing reaction
if (currentReaction != null)
{ {
if (reactionEnum.HasValue) content.Reactions.Remove(currentReaction);
{
var reaction = new ContentReaction
{
Reaction = reactionEnum.Value,
UserId = req.UserId,
UserName = req.UserName
};
content.Reactions.Add(reaction);
}
} }
// If the new reaction is valid, add or update the reaction
if (reactionEnum.HasValue)
{
var reaction = new ContentReaction
{
Reaction = reactionEnum.Value,
UserId = req.UserId,
UserName = req.UserName
};
content.Reactions.Add(reaction);
}
await context.SaveChangesAsync(ct); await context.SaveChangesAsync(ct);
} }
} }