using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
namespace EnvelopeGenerator.Application.Configs;
///
///
///
public class DefaultReadConfigQuery : IRequest
{
///
///
///
public static readonly Guid MemoryCacheKey = Guid.NewGuid();
}
///
///
///
public static class DefaultReadConfigQueryExtensions
{
///
///
///
///
///
///
public static Task ReadDefaultConfigAsync(this ISender sender, CancellationToken cancel = default)
=> sender.Send(new DefaultReadConfigQuery(), cancel);
}
///
///
///
public class DefaultReadConfigQueryHandler : IRequestHandler
{
private readonly IRepository _repo;
private readonly IMapper _mapper;
private readonly IMemoryCache _cache;
///
///
///
///
///
///
public DefaultReadConfigQueryHandler(IRepository repo, IMapper mapper, IMemoryCache cache)
{
_repo = repo;
_mapper = mapper;
_cache = cache;
}
///
///
///
///
///
///
///
public async Task Handle(DefaultReadConfigQuery request, CancellationToken cancel)
{
var config = await _cache.GetOrCreateAsync(DefaultReadConfigQuery.MemoryCacheKey, async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
var configs = await _repo.GetAllAsync(cancel);
var defaultConfig = configs.FirstOrDefault();
var defaultConfigDto = _mapper.Map(defaultConfig);
return defaultConfigDto;
});
if(config is null)
{
_cache.Remove(DefaultReadConfigQuery.MemoryCacheKey);
throw new NotFoundException("No configuration record is found.");
}
return config;
}
}