Handler.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. {
  7. public sealed class Handler(IAppDbContext db, ICacheService cache) : IQueryHandler<Query, Response?>
  8. {
  9. public async Task<Response?> Handle(Query request, CancellationToken ct)
  10. {
  11. var cacheKey = CacheKeys.DocumentByCode(request.Code);
  12. var cached = await cache.GetAsync<Response>(cacheKey, ct);
  13. if (cached is not null)
  14. {
  15. return cached;
  16. }
  17. var document = await db.Document.AsNoTracking().Where(c => c.IsActive).FirstOrDefaultAsync(c => c.Code == request.Code, ct);
  18. if (document is null)
  19. {
  20. return null;
  21. }
  22. var response = new Response
  23. {
  24. ID = document.ID,
  25. Code = document.Code,
  26. Subject = document.Subject,
  27. Content = document.Content,
  28. IsActive = document.IsActive,
  29. UpdatedAt = document.UpdatedAt,
  30. CreatedAt = document.CreatedAt
  31. };
  32. await cache.SetAsync(cacheKey, response, ct);
  33. return response;
  34. }
  35. }
  36. }