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 a custom exception produced by /// when the response is null or an empty collection. /// /// The expected response type. /// The exception type to throw. /// The mediator instance. /// The MediatR request whose response may be null. /// A factory that creates the exception to throw when the response is absent. /// Cancellation token. /// A guaranteed non-null . /// The exception produced by . public static async Task GetOrThrow(this ISender sender, IRequest request, Func exceptionFactory, CancellationToken cancel = default) where TException : Exception { if (await sender.Send(request, cancel) is TResponse res) { if (res is not string && res is IEnumerable enumerable && !enumerable.Cast().Any()) throw exceptionFactory(); return res; } throw exceptionFactory(); } /// /// 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 GetOrThrow(this ISender sender, IRequest request, string? exceptionMessage, CancellationToken cancel = default) => await sender.GetOrThrow(request, () => new NotFoundException(exceptionMessage ?? $"The requested resource of type {typeof(TResponse).Name} was not found."), cancel); /// public static async Task GetOrThrow(this ISender sender, IRequest request, CancellationToken cancel = default) => await sender.GetOrThrow(request, null, cancel); }