Handler.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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.ToggleBookmark;
  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 post = await db.FeedPost.FirstOrDefaultAsync(p => p.ID == request.PostID && !p.IsDeleted, ct);
  12. if (post is null)
  13. {
  14. return Result.Failure<Response>(Error.NotFound("Feed.PostNotFound", "게시글을 찾을 수 없습니다."));
  15. }
  16. var existing = await db.FeedBookmark.FirstOrDefaultAsync(b => b.FeedPostID == request.PostID && b.MemberID == request.MemberID, ct);
  17. bool hasBookmark;
  18. if (existing is null)
  19. {
  20. await db.FeedBookmark.AddAsync(new FeedBookmark
  21. {
  22. FeedPostID = request.PostID,
  23. MemberID = request.MemberID
  24. }, ct);
  25. post.Bookmarks++;
  26. hasBookmark = true;
  27. }
  28. else
  29. {
  30. db.FeedBookmark.Remove(existing);
  31. post.Bookmarks = post.Bookmarks > 0 ? post.Bookmarks - 1 : 0;
  32. hasBookmark = false;
  33. }
  34. await db.SaveChangesAsync(ct);
  35. return new Response(hasBookmark, post.Bookmarks);
  36. }
  37. }