Handler.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using Microsoft.EntityFrameworkCore;
  4. using SharedKernel.Results;
  5. namespace Application.Features.Api.Forum.Comment.Delete;
  6. public sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result>
  7. {
  8. public async Task<Result> Handle(Command request, CancellationToken ct)
  9. {
  10. var comment = await db.Comment.FirstOrDefaultAsync(x => x.ID == request.ID, ct);
  11. if (comment is null)
  12. {
  13. return Result.Failure(Error.NotFound("Comment.NotFound", "댓글을 찾을 수 없습니다."));
  14. }
  15. if (comment.MemberID != request.MemberID)
  16. {
  17. return Result.Failure(Error.Forbidden("Comment.Forbidden", "삭제 권한이 없습니다."));
  18. }
  19. comment.IsDeleted = true;
  20. comment.DeletedAt = DateTime.UtcNow;
  21. // Post 댓글 카운트 감소
  22. var post = await db.Post.FirstOrDefaultAsync(x => x.ID == comment.PostID, ct);
  23. if (post is not null)
  24. {
  25. post.Comments--;
  26. post.UpdatedAt = DateTime.UtcNow;
  27. }
  28. // Board 댓글 카운트 감소
  29. var board = await db.Board.FirstOrDefaultAsync(x => x.ID == comment.BoardID, ct);
  30. if (board is not null)
  31. {
  32. board.Comments--;
  33. board.UpdatedAt = DateTime.UtcNow;
  34. }
  35. // MemberStats 댓글 수 감소
  36. var memberStats = await db.MemberStats.FirstOrDefaultAsync(x => x.MemberID == comment.MemberID, ct);
  37. if (memberStats is not null)
  38. {
  39. memberStats.CommentCount--;
  40. }
  41. await db.SaveChangesAsync(ct);
  42. return Result.Success();
  43. }
  44. }