-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathResult.cs
104 lines (92 loc) · 2.92 KB
/
Result.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.PWABuilder.ManifestCreator
{
/// <summary>
/// Represents a result or exception.
/// </summary>
/// <typeparam name="T"></typeparam>
public struct Result<T>
{
public Result(T? value)
{
this.Value = value;
this.Error = null;
}
public Result(T? value, Exception? error)
{
this.Value = value;
this.Error = error;
}
public T? Value { get; init; }
public Exception? Error { get; init; }
public void Deconstruct(out T? value, out Exception? error)
{
value = this.Value;
error = this.Error;
}
public Result<TOther> Pipe<TOther>(Func<T, TOther?> selector)
{
if (this.Value == null)
{
return new Result<TOther>(default, this.Error);
}
var val = selector(this.Value);
return new Result<TOther>(val);
}
public T ValueOr(Func<T> creator)
{
return this.Value ?? creator();
}
public static implicit operator Result<T>(T result) => new Result<T>(result);
public static implicit operator Result<T>(Exception error) => new Result<T>(default, error);
}
public static class ResultExtensions
{
public static async Task<Result<TOther>> PipeAsync<T, TOther>(this Task<Result<T>> task, Func<T, Task<TOther>> selector)
{
try
{
var val = await task;
if (val.Value != null)
{
var other = await selector(val.Value);
return new Result<TOther>(other, val.Error);
}
else
{
return new Result<TOther>(default, val.Error);
}
}
catch (Exception error)
{
return new Result<TOther>(default, error);
}
}
public static async Task<Result<TOther>> PipeAsync<T, TOther>(this Task<Result<T>> task, Func<T, Task<Result<TOther>>> selector)
{
try
{
var val = await task;
if (val.Error != null)
{
return new Result<TOther>(default, val.Error);
}
var selectedResult = val.Pipe(selector);
if (selectedResult.Value != null)
{
var other = await selectedResult.Value;
return other;
}
return new Result<TOther>(default, selectedResult.Error);
}
catch (Exception error)
{
return new Result<TOther>(default, error);
}
}
}
}