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.
78 lines
2.6 KiB
C#
78 lines
2.6 KiB
C#
using MediatR;
|
|
using EnvelopeGenerator.Application.Common.Query;
|
|
using EnvelopeGenerator.Application.Common.Dto;
|
|
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>
|
|
{
|
|
/// <summary>
|
|
/// Optionaler Benutzerfilter; wenn gesetzt, werden nur Umschläge des Benutzers geladen.
|
|
/// </summary>
|
|
public int? UserId { get; init; }
|
|
|
|
/// <summary>
|
|
/// Setzt den Benutzerkontext für die Abfrage.
|
|
/// </summary>
|
|
public ReadSingleEnvelopeQuery Authorize(int userId) => this with { UserId = userId };
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verarbeitet <see cref="ReadSingleEnvelopeQuery"/> und liefert ein einzelnes <see cref="EnvelopeDto"/>-Ergebnis.
|
|
/// </summary>
|
|
public class ReadSingleEnvelopeQueryHandler : IRequestHandler<ReadSingleEnvelopeQuery, EnvelopeDto>
|
|
{
|
|
private readonly IRepository<Envelope> _repository;
|
|
private readonly IMapper _mapper;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="repository"></param>
|
|
/// <param name="mapper"></param>
|
|
public ReadSingleEnvelopeQueryHandler(IRepository<Envelope> repository, IMapper mapper)
|
|
{
|
|
_repository = repository;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="cancel"></param>
|
|
/// <returns></returns>
|
|
public async Task<EnvelopeDto> Handle(ReadSingleEnvelopeQuery request, CancellationToken cancel)
|
|
{
|
|
var query = _repository.Query;
|
|
|
|
if (request.UserId is int userId)
|
|
query = query.Where(e => e.UserId == userId);
|
|
|
|
if (request.Id is int id)
|
|
query = query.Where(e => e.Id == id);
|
|
|
|
if (request.Uuid is string uuid)
|
|
query = query.Where(e => e.Uuid == uuid);
|
|
|
|
var envelopes = await query
|
|
.Include(e => e.Documents)
|
|
.Take(2)
|
|
.ToListAsync(cancel);
|
|
|
|
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");
|
|
}
|
|
} |