Handler.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using SharedKernel.Results;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Api.MyPage.GetComments;
  6. internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Result<Response>>
  7. {
  8. public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
  9. {
  10. var page = request.Page < 1 ? 1 : request.Page;
  11. var perPage = request.PerPage is < 1 or > 50 ? 20 : request.PerPage;
  12. var query = db.Comment.AsNoTracking().Where(c => c.MemberID == request.MemberID && !c.IsDeleted).OrderByDescending(c => c.ID);
  13. var total = await query.CountAsync(ct);
  14. var list = await query
  15. .Skip((page - 1) * perPage)
  16. .Take(perPage)
  17. .Select(c => new
  18. {
  19. c.ID,
  20. c.PostID,
  21. PostSubject = c.Post.Subject,
  22. c.BoardID,
  23. BoardName = c.Board.Name,
  24. c.Content,
  25. c.Likes,
  26. c.CreatedAt
  27. })
  28. .ToListAsync(ct);
  29. var startNum = total - ((page - 1) * perPage);
  30. return Result.Success(new Response(
  31. [..list.Select((c, i) => new CommentItem(
  32. Num: startNum - i,
  33. c.ID,
  34. c.PostID,
  35. c.PostSubject,
  36. c.BoardID,
  37. c.BoardName,
  38. c.Content.Length > 100 ? c.Content[..100] + "..." : c.Content,
  39. c.Likes,
  40. c.CreatedAt
  41. ))],
  42. total,
  43. page,
  44. perPage
  45. ));
  46. }
  47. }