Added EnforceSingleResult to ReadDefaultConfigQuery to allow strict single-result enforcement. Updated handler logic to use SingleOrDefaultAsync when requested. Replaced InvalidOperationException with NotFoundException and improved error messaging when no configuration is found.
57 lines
1.7 KiB
C#
57 lines
1.7 KiB
C#
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.EntityFrameworkCore;
|
|
|
|
namespace EnvelopeGenerator.Application.Configuration.Queries;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public record ReadDefaultConfigQuery : IRequest<ConfigDto>
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public bool EnforceSingleResult { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public class ReadDefaultConfigQueryHandler : IRequestHandler<ReadDefaultConfigQuery, ConfigDto>
|
|
{
|
|
private readonly IRepository<Config> _repo;
|
|
|
|
private readonly IMapper _mapper;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="repo"></param>
|
|
/// <param name="mapper"></param>
|
|
public ReadDefaultConfigQueryHandler(IRepository<Config> repo, IMapper mapper)
|
|
{
|
|
_repo = repo;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="cancel"></param>
|
|
/// <returns></returns>
|
|
/// <exception cref="InvalidOperationException"></exception>
|
|
public async Task<ConfigDto> Handle(ReadDefaultConfigQuery request, CancellationToken cancel)
|
|
{
|
|
var config = request.EnforceSingleResult
|
|
? await _repo.Query.SingleOrDefaultAsync(cancel)
|
|
: await _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<ConfigDto>(config);
|
|
}
|
|
} |