54 lines
2.2 KiB
C#

using DigitalData.Core.Exceptions;
namespace EnvelopeGenerator.Application.Extensions;
/// <summary>
/// Extension methods for tasks
/// </summary>
public static class TaskExtensions
{
/// <summary>
/// Awaits the specified task and ensures that the result is not <c>null</c>.
/// If the result is <c>null</c>, a <see cref="NotFoundException"/> is thrown.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="task">The task to await.</param>
/// <param name="exceptionMessage">Optional custom exception message.</param>
/// <returns>The awaited result if not <c>null</c>.</returns>
/// <exception cref="NotFoundException">Thrown if the result is <c>null</c>.</exception>
public static async Task<T> ThrowIfNull<T>(this Task<T?> task, string? exceptionMessage = null)
{
var result = await task;
return result ?? throw new NotFoundException(exceptionMessage);
}
/// <summary>
/// Awaits the specified task and ensures that the result is not <c>empty</c>.
/// If the result contains no elements, a <see cref="NotFoundException"/> is thrown.
/// </summary>
/// <typeparam name="T">The element type of the collection.</typeparam>
/// <param name="task">The task to await.</param>
/// <param name="exceptionMessage">Optional custom exception message.</param>
/// <returns>The awaited collection if it is not <c>null</c> or empty.</returns>
/// <exception cref="NotFoundException">Thrown if the result is <c>null</c> or empty.</exception>
public static async Task<IEnumerable<T>> ThrowIfNull<T>(this Task<IEnumerable<T>> task, string? exceptionMessage = null)
{
var result = await task;
return result?.Any() ?? false ? result : throw new NotFoundException(exceptionMessage);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="I"></typeparam>
/// <param name="task"></param>
/// <param name="act"></param>
/// <returns></returns>
public static async Task<I> Then<T, I>(this Task<T> task, Func<T, I> act)
{
var res = await task;
return act(res);
}
}