Handler.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using Application.Abstractions.Cache;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Api.Popup.GetAll;
  6. public sealed class Handler(IAppDbContext db, ICacheService cache) : IQueryHandler<Query, Response>
  7. {
  8. public async Task<Response> Handle(Query request, CancellationToken ct)
  9. {
  10. var cacheKey = CacheKeys.PopupByCode(request.Code);
  11. var cached = await cache.GetAsync<Response>(cacheKey, ct);
  12. if (cached is not null)
  13. {
  14. return cached;
  15. }
  16. var query = db.Popup.AsNoTracking().Where(x => x.PopupPosition.Code == request.Code);
  17. var total = await query.CountAsync(ct);
  18. var list = await query
  19. .OrderBy(x => x.Order)
  20. .ThenByDescending(x => x.ID)
  21. .Select(x => new
  22. {
  23. x.ID,
  24. x.PositionID,
  25. x.Subject,
  26. x.Content,
  27. x.Link,
  28. x.StartAt,
  29. x.EndAt,
  30. x.Order,
  31. x.IsActive,
  32. x.UpdatedAt,
  33. x.CreatedAt
  34. })
  35. .ToListAsync(ct);
  36. var response = new Response
  37. {
  38. Total = total,
  39. List = [..list.Select(x => new Response.Row
  40. {
  41. ID = x.ID,
  42. PositionID = x.PositionID,
  43. Subject = x.Subject,
  44. Content = x.Content,
  45. Link = x.Link,
  46. StartAt = x.StartAt,
  47. EndAt = x.EndAt,
  48. Order = x.Order,
  49. IsActive = x.IsActive,
  50. UpdatedAt = x.UpdatedAt,
  51. CreatedAt = x.CreatedAt
  52. })]
  53. };
  54. await cache.SetAsync(cacheKey, response, ct);
  55. return response;
  56. }
  57. }