| | 1 | | // ReSharper disable MemberCanBePrivate.Global |
| | 2 | | // ReSharper disable UnusedAutoPropertyAccessor.Global |
| | 3 | |
|
| | 4 | | using planora.Domain.Errors; |
| | 5 | |
|
| | 6 | | namespace planora.Application.Common; |
| | 7 | |
|
| | 8 | | public class Result |
| | 9 | | { |
| | 10 | | protected Result(bool isSuccess, AppError? error) |
| | 11 | | { |
| | 12 | | if ((isSuccess && error is not null) || |
| | 13 | | (!isSuccess && error is null)) |
| | 14 | | { |
| | 15 | | throw new ArgumentException("Invalid error", nameof(error)); |
| | 16 | | } |
| | 17 | |
|
| | 18 | | IsSuccess = isSuccess; |
| | 19 | | Error = error; |
| | 20 | | } |
| | 21 | |
|
| | 22 | | public bool IsSuccess { get; } |
| | 23 | | public AppError? Error { get; } |
| | 24 | |
|
| | 25 | | public static Result Success() |
| | 26 | | { |
| | 27 | | return new Result(true, null); |
| | 28 | | } |
| | 29 | |
|
| | 30 | | public static Result<TValue> Success<TValue>(TValue value) |
| | 31 | | { |
| | 32 | | return new Result<TValue>(value, true, null); |
| | 33 | | } |
| | 34 | |
|
| | 35 | |
|
| | 36 | | public static Result Failure(AppError appError) |
| | 37 | | { |
| | 38 | | return new Result(false, appError); |
| | 39 | | } |
| | 40 | |
|
| | 41 | | public static Result<TValue> Failure<TValue>(AppError appError) |
| | 42 | | { |
| | 43 | | return new Result<TValue>(default, false, appError); |
| | 44 | | } |
| | 45 | |
|
| | 46 | | // Implicit conversion from AppError to Result (failure) |
| | 47 | | public static implicit operator Result(AppError appError) |
| | 48 | | { |
| | 49 | | return Failure(appError); |
| | 50 | | } |
| | 51 | | } |
| | 52 | |
|
| 18 | 53 | | public class Result<TValue>(TValue? data, bool isSuccess, AppError? error) : Result(isSuccess, error) |
| | 54 | | { |
| | 55 | | public TValue Data |
| | 56 | | { |
| | 57 | | get |
| | 58 | | { |
| 16 | 59 | | if (!IsSuccess) |
| | 60 | | { |
| 2 | 61 | | throw new InvalidOperationException("Cannot access the data of a failed result"); |
| | 62 | | } |
| | 63 | |
|
| 14 | 64 | | return data!; |
| | 65 | | } |
| | 66 | | } |
| | 67 | |
|
| | 68 | |
|
| | 69 | | // Implicit conversion from TValue to Result<TValue> (success) |
| | 70 | | public static implicit operator Result<TValue>(TValue value) |
| | 71 | | { |
| 6 | 72 | | return Success(value); |
| | 73 | | } |
| | 74 | |
|
| | 75 | | // Implicit conversion from AppError to Result<TValue> (failure) |
| | 76 | | public static implicit operator Result<TValue>(AppError appError) |
| | 77 | | { |
| 4 | 78 | | return Failure<TValue>(appError); |
| | 79 | | } |
| | 80 | | } |