Handler.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using SharedKernel.Results;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Api.MyPage.GetPosts;
  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.Post.AsNoTracking().Where(p => p.MemberID == request.MemberID && !p.IsDeleted).OrderByDescending(p => p.ID);
  13. var total = await query.CountAsync(ct);
  14. var list = await query
  15. .Skip((page - 1) * perPage)
  16. .Take(perPage)
  17. .Select(p => new
  18. {
  19. p.ID,
  20. p.BoardID,
  21. BoardName = p.Board.Name,
  22. p.Subject,
  23. p.IsSecret,
  24. p.IsReply,
  25. p.Views,
  26. p.Likes,
  27. p.Comments,
  28. p.Images,
  29. p.Medias,
  30. p.Files,
  31. p.CreatedAt
  32. })
  33. .ToListAsync(ct);
  34. var startNum = total - ((page - 1) * perPage);
  35. return Result.Success(new Response(
  36. [..list.Select((p, i) => new PostItem(
  37. Num: startNum - i,
  38. p.ID,
  39. p.BoardID,
  40. p.BoardName,
  41. p.Subject,
  42. p.IsSecret,
  43. p.IsReply,
  44. p.Views,
  45. p.Likes,
  46. p.Comments,
  47. p.Images,
  48. p.Medias,
  49. p.Files,
  50. p.CreatedAt
  51. ))],
  52. total,
  53. page,
  54. perPage
  55. ));
  56. }
  57. }