-
Notifications
You must be signed in to change notification settings - Fork 122
Description
Summary:
Currently, we have extension methods that allow mapping between different types within Result. However, there's no straightforward way to map a Result to a non-generic Result (i.e., without T). I propose adding a new Map extension method to handle this scenario.
Problem:
When working with the Result class, there are cases where we want to discard the value T and map it to a non-generic Result. This is useful when we care about the success or failure state of the operation but no longer need to carry forward the result value.
Proposed Solution:
Add an extension method to the Result class that allows mapping from Result to Result. This extension method will preserve the success or failure status, as well as any errors, but will discard the underlying value T.
public static Ardalis.Result.Result Map<TSource>(this Result<TSource> result)
{
switch (result.Status)
{
case ResultStatus.Ok: return Ardalis.Result.Result.Success();
case ResultStatus.NotFound: return result.Errors.Any()
? Ardalis.Result.Result.NotFound(result.Errors.ToArray())
: Ardalis.Result.Result.NotFound();
case ResultStatus.Unauthorized: return result.Errors.Any()
? Ardalis.Result.Result.Unauthorized(result.Errors.ToArray())
: Ardalis.Result.Result.Unauthorized();
case ResultStatus.Forbidden: return result.Errors.Any()
? Ardalis.Result.Result.Forbidden(result.Errors.ToArray())
: Ardalis.Result.Result.Forbidden();
case ResultStatus.Invalid: return Ardalis.Result.Result.Invalid(result.ValidationErrors);
case ResultStatus.Error: return Ardalis.Result.Result.Error(new ErrorList(result.Errors.ToArray(), result.CorrelationId));
case ResultStatus.Conflict: return result.Errors.Any()
? Ardalis.Result.Result.Conflict(result.Errors.ToArray())
: Ardalis.Result.Result.Conflict();
case ResultStatus.CriticalError: return Ardalis.Result.Result.CriticalError(result.Errors.ToArray());
case ResultStatus.Unavailable: return Ardalis.Result.Result.Unavailable(result.Errors.ToArray());
case ResultStatus.NoContent: return Ardalis.Result.Result.NoContent();
default:
throw new NotSupportedException($"Result {result.Status} conversion is not supported.");
}
}
Sample ### Method Signature:
This will make it easier to handle cases where the result value is no longer needed, and we only care about whether the operation succeeded or failed.
Benefits:
Provides a clean and reusable way to convert Result to Result.
Keeps the codebase cleaner by removing the need for custom mapping logic in different parts of the code.