added Match with fallback extensions
Some checks failed
.NET Test / test (push) Successful in 4m19s
.NET Publish / publish (push) Failing after 3m8s

This commit is contained in:
2023-12-13 18:30:38 +04:00
parent 7aaacb0ac7
commit 5a2ae19a8e

View File

@@ -2,6 +2,80 @@ namespace Just.Railway;
public static partial class ResultExtensions public static partial class ResultExtensions
{ {
#region Match (with fallback)
public static T Match<T>(this in Result<T> result, Func<Error, T> fallback)
{
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => fallback(result.Error!),
_ => throw new ResultNotInitializedException(nameof(result))
};
}
public static async Task<T> Match<T>(this Result<T> result, Func<Error, Task<T>> fallback)
{
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => await fallback(result.Error!).ConfigureAwait(false),
_ => throw new ResultNotInitializedException(nameof(result))
};
}
public static async Task<T> Match<T>(this Task<Result<T>> resultTask, Func<Error, T> fallback)
{
var result = await resultTask.ConfigureAwait(false);
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => fallback(result.Error!),
_ => throw new ResultNotInitializedException(nameof(resultTask))
};
}
public static async Task<T> Match<T>(this Task<Result<T>> resultTask, Func<Error, Task<T>> fallback)
{
var result = await resultTask.ConfigureAwait(false);
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => await fallback(result.Error!).ConfigureAwait(false),
_ => throw new ResultNotInitializedException(nameof(resultTask))
};
}
public static async ValueTask<T> Match<T>(this Result<T> result, Func<Error, ValueTask<T>> fallback)
{
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => await fallback(result.Error!).ConfigureAwait(false),
_ => throw new ResultNotInitializedException(nameof(result))
};
}
public static async ValueTask<T> Match<T>(this ValueTask<Result<T>> resultTask, Func<Error, T> fallback)
{
var result = await resultTask.ConfigureAwait(false);
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => fallback(result.Error!),
_ => throw new ResultNotInitializedException(nameof(resultTask))
};
}
public static async ValueTask<T> Match<T>(this ValueTask<Result<T>> resultTask, Func<Error, ValueTask<T>> fallback)
{
var result = await resultTask.ConfigureAwait(false);
return result.State switch
{
ResultState.Success => result.Value,
ResultState.Error => await fallback(result.Error!).ConfigureAwait(false),
_ => throw new ResultNotInitializedException(nameof(resultTask))
};
}
#endregion
#region Merge #region Merge
public static Result Merge(this IEnumerable<Result> results) public static Result Merge(this IEnumerable<Result> results)