| | 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 | | { |
| 34 | 10 | | protected Result(bool isSuccess, AppError? error) |
| | 11 | | { |
| 34 | 12 | | if ((isSuccess && error is not null) || |
| 34 | 13 | | (!isSuccess && error is null)) |
| | 14 | | { |
| 0 | 15 | | throw new ArgumentException("Invalid error", nameof(error)); |
| | 16 | | } |
| | 17 | |
|
| 34 | 18 | | IsSuccess = isSuccess; |
| 34 | 19 | | Error = error; |
| 34 | 20 | | } |
| | 21 | |
|
| 50 | 22 | | public bool IsSuccess { get; } |
| 24 | 23 | | public AppError? Error { get; } |
| | 24 | |
|
| | 25 | | public static Result Success() |
| | 26 | | { |
| 6 | 27 | | return new Result(true, null); |
| | 28 | | } |
| | 29 | |
|
| | 30 | | public static Result<TValue> Success<TValue>(TValue value) |
| | 31 | | { |
| 12 | 32 | | return new Result<TValue>(value, true, null); |
| | 33 | | } |
| | 34 | |
|
| | 35 | |
|
| | 36 | | public static Result Failure(AppError appError) |
| | 37 | | { |
| 10 | 38 | | return new Result(false, appError); |
| | 39 | | } |
| | 40 | |
|
| | 41 | | public static Result<TValue> Failure<TValue>(AppError appError) |
| | 42 | | { |
| 6 | 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 | | { |
| 8 | 49 | | return Failure(appError); |
| | 50 | | } |
| | 51 | | } |
| | 52 | |
|
| | 53 | | public class Result<TValue>(TValue? data, bool isSuccess, AppError? error) : Result(isSuccess, error) |
| | 54 | | { |
| | 55 | | public TValue Data |
| | 56 | | { |
| | 57 | | get |
| | 58 | | { |
| | 59 | | if (!IsSuccess) |
| | 60 | | { |
| | 61 | | throw new InvalidOperationException("Cannot access the data of a failed result"); |
| | 62 | | } |
| | 63 | |
|
| | 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 | | { |
| | 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 | | { |
| | 78 | | return Failure<TValue>(appError); |
| | 79 | | } |
| | 80 | | } |