Handler.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Domain.Entities.Feed;
  4. using Microsoft.EntityFrameworkCore;
  5. using SharedKernel.Results;
  6. namespace Application.Features.Api.Feed.ToggleCommentLike;
  7. public sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result<Response>>
  8. {
  9. public async Task<Result<Response>> Handle(Command request, CancellationToken ct)
  10. {
  11. var comment = await db.FeedComment.FirstOrDefaultAsync(c => c.ID == request.CommentID && !c.IsDeleted, ct);
  12. if (comment is null)
  13. {
  14. return Result.Failure<Response>(Error.NotFound("Feed.CommentNotFound", "댓글을 찾을 수 없습니다."));
  15. }
  16. var existing = await db.FeedCommentLike.FirstOrDefaultAsync(l => l.FeedCommentID == request.CommentID && l.MemberID == request.MemberID, ct);
  17. bool hasLike;
  18. if (existing is null)
  19. {
  20. await db.FeedCommentLike.AddAsync(new FeedCommentLike
  21. {
  22. FeedPostID = comment.FeedPostID,
  23. FeedCommentID = request.CommentID,
  24. MemberID = request.MemberID
  25. }, ct);
  26. comment.Likes++;
  27. comment.Score = comment.Likes;
  28. hasLike = true;
  29. }
  30. else
  31. {
  32. db.FeedCommentLike.Remove(existing);
  33. comment.Likes = comment.Likes > 0 ? comment.Likes - 1 : 0;
  34. comment.Score = comment.Likes;
  35. hasLike = false;
  36. }
  37. await db.SaveChangesAsync(ct);
  38. return new Response(hasLike, comment.Likes);
  39. }
  40. }