diff --git a/EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs b/EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs new file mode 100644 index 00000000..ea971903 --- /dev/null +++ b/EnvelopeGenerator.Application/Common/Extensions/MediatorExtensions.cs @@ -0,0 +1,38 @@ +using System.Collections; +using DigitalData.Core.Exceptions; +using MediatR; + +namespace EnvelopeGenerator.Application.Common.Extensions; + +/// +/// Extension methods for that enforce non-null and non-empty responses. +/// +public static class MediatorExtensions +{ + /// + /// Sends a request via MediatR and throws when the response is null or an empty collection. + /// + /// The expected response type. + /// The mediator instance. + /// The MediatR request whose response may be null. + /// Optional message for the . + /// Cancellation token. + /// A guaranteed non-null . + /// Thrown when the response is null or an empty collection. + public static async Task SendOrNotFoundAsync(this IMediator mediator, IRequest request, string? exceptionMessage, CancellationToken cancellationToken = default) + { + if(await mediator.Send(request, cancellationToken) is TResponse res) + { + if(res is IEnumerable enumerable && !enumerable.Cast().Any()) + throw new NotFoundException(exceptionMessage); + + return res; + } + + throw new NotFoundException(exceptionMessage); + } + + /// + public static async Task SendOrNotFoundAsync(this IMediator mediator, IRequest request, CancellationToken cancellationToken = default) + => await mediator.SendOrNotFoundAsync(request, null, cancellationToken); +} \ No newline at end of file