Add EnforceSingleResult to config query and improve errors
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.
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
using AutoMapper;
|
using AutoMapper;
|
||||||
using DigitalData.Core.Abstraction.Application.Repository;
|
using DigitalData.Core.Abstraction.Application.Repository;
|
||||||
|
using DigitalData.Core.Exceptions;
|
||||||
using EnvelopeGenerator.Application.Common.Dto;
|
using EnvelopeGenerator.Application.Common.Dto;
|
||||||
using EnvelopeGenerator.Domain.Entities;
|
using EnvelopeGenerator.Domain.Entities;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
@@ -12,6 +13,10 @@ namespace EnvelopeGenerator.Application.Configuration.Queries;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public record ReadDefaultConfigQuery : IRequest<ConfigDto>
|
public record ReadDefaultConfigQuery : IRequest<ConfigDto>
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public bool EnforceSingleResult { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -43,7 +48,10 @@ public class ReadDefaultConfigQueryHandler : IRequestHandler<ReadDefaultConfigQu
|
|||||||
/// <exception cref="InvalidOperationException"></exception>
|
/// <exception cref="InvalidOperationException"></exception>
|
||||||
public async Task<ConfigDto> Handle(ReadDefaultConfigQuery request, CancellationToken cancel)
|
public async Task<ConfigDto> Handle(ReadDefaultConfigQuery request, CancellationToken cancel)
|
||||||
{
|
{
|
||||||
var config = await _repo.Query.FirstOrDefaultAsync(cancel) ?? throw new InvalidOperationException("No configuration found.");
|
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);
|
return _mapper.Map<ConfigDto>(config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user