using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Common;
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
namespace EnvelopeGenerator.Application.Configuration.Queries;
///
///
///
public record ReadDefaultConfigQuery : IRequest
{
///
///
///
public bool EnforceSingleResult { get; init; }
}
///
///
///
public class ReadDefaultConfigQueryHandler : IRequestHandler
{
private readonly IRepository _repo;
private readonly IMapper _mapper;
private readonly IMemoryCache _cache;
///
///
///
///
///
///
public ReadDefaultConfigQueryHandler(IRepository repo, IMapper mapper, IMemoryCache cache)
{
_repo = repo;
_mapper = mapper;
_cache = cache;
}
///
///
///
///
///
///
///
public async Task Handle(ReadDefaultConfigQuery request, CancellationToken cancel)
{
var config = await _cache.GetOrCreateAsync(CacheKey.DefaultConfig, entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30);
return request.EnforceSingleResult
? _repo.Query.SingleOrDefaultAsync(cancel)
: _repo.Query.FirstOrDefaultAsync(cancel)
?? throw new NotFoundException("Default configuration could not be found. Ensure at least one configuration record exists in the database.");
});
return _mapper.Map(config);
}
}