Handler.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using Application.Abstractions.Cache;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Api.Document.GetByCode;
  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.DocumentByCode(request.Code);
  11. var cached = await cache.GetAsync<Response>(cacheKey, ct);
  12. if (cached is not null)
  13. {
  14. return cached;
  15. }
  16. var document = await db.Document.AsNoTracking().Where(c => c.IsActive).FirstOrDefaultAsync(c => c.Code == request.Code, ct);
  17. if (document is null)
  18. {
  19. return null;
  20. }
  21. var response = new Response
  22. {
  23. ID = document.ID,
  24. Code = document.Code,
  25. Subject = document.Subject,
  26. Content = document.Content,
  27. IsActive = document.IsActive,
  28. UpdatedAt = document.UpdatedAt,
  29. CreatedAt = document.CreatedAt
  30. };
  31. await cache.SetAsync(cacheKey, response, ct);
  32. return response;
  33. }
  34. }