Refactor envelope query to throw on not found or multiple

Refactored ReadSingleEnvelopeQuery and its handler to return EnvelopeDto directly and throw NotFoundException or BadRequestException when no or multiple envelopes are found, instead of returning null. Updated imports to include custom exceptions.
This commit is contained in:
2026-04-09 10:28:13 +02:00
parent a7cfb099fa
commit 2d8375f26a

View File

@@ -5,13 +5,14 @@ using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using DigitalData.Core.Exceptions;
namespace EnvelopeGenerator.Application.Envelopes.Queries;
/// <summary>
/// Repräsentiert eine Abfrage für einen einzelnen Umschlag.
/// </summary>
public record ReadSingleEnvelopeQuery : EnvelopeQueryBase, IRequest<EnvelopeDto?>
public record ReadSingleEnvelopeQuery : EnvelopeQueryBase, IRequest<EnvelopeDto>
{
/// <summary>
/// Optionaler Benutzerfilter; wenn gesetzt, werden nur Umschläge des Benutzers geladen.
@@ -27,7 +28,7 @@ public record ReadSingleEnvelopeQuery : EnvelopeQueryBase, IRequest<EnvelopeDto?
/// <summary>
/// Verarbeitet <see cref="ReadSingleEnvelopeQuery"/> und liefert ein einzelnes <see cref="EnvelopeDto"/>-Ergebnis.
/// </summary>
public class ReadSingleEnvelopeQueryHandler : IRequestHandler<ReadSingleEnvelopeQuery, EnvelopeDto?>
public class ReadSingleEnvelopeQueryHandler : IRequestHandler<ReadSingleEnvelopeQuery, EnvelopeDto>
{
private readonly IRepository<Envelope> _repository;
private readonly IMapper _mapper;
@@ -49,7 +50,7 @@ public class ReadSingleEnvelopeQueryHandler : IRequestHandler<ReadSingleEnvelope
/// <param name="request"></param>
/// <param name="cancel"></param>
/// <returns></returns>
public async Task<EnvelopeDto?> Handle(ReadSingleEnvelopeQuery request, CancellationToken cancel)
public async Task<EnvelopeDto> Handle(ReadSingleEnvelopeQuery request, CancellationToken cancel)
{
var query = _repository.Query;
@@ -61,11 +62,17 @@ public class ReadSingleEnvelopeQueryHandler : IRequestHandler<ReadSingleEnvelope
if (request.Uuid is string uuid)
query = query.Where(e => e.Uuid == uuid);
var envelope = await query
var envelopes = await query
.Include(e => e.Documents)
.FirstOrDefaultAsync(cancel);
.Take(2)
.ToListAsync(cancel);
return envelope is null ? null : _mapper.Map<EnvelopeDto>(envelope);
if (envelopes.Count > 1)
throw new BadRequestException($"Multiple envelopes found for the given criteria: Id={request.Id}, Uuid={request.Uuid}, UserId={request.UserId}");
return envelopes.SingleOrDefault() is Envelope envelope
? _mapper.Map<EnvelopeDto>(envelope)
: throw new NotFoundException($"Envelope with Id={request.Id}, Uuid={request.Uuid} not found");
}
}
}