Last active
February 3, 2021 11:39
-
-
Save jovaneyck/654cbb2ba28da9d1adc470fec5887196 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Threading.Tasks; | |
using LanguageExt; | |
using Xunit; | |
namespace LanguageExtDemo | |
{ | |
public class Repository | |
{ | |
public OptionAsync<string> GetName(int id) | |
{ | |
if(id == 1) | |
return "Jo"; | |
if(id == 2) | |
return "Ruben"; | |
return OptionAsync<string>.None; | |
} | |
} | |
public class HttpAgent | |
{ | |
public EitherAsync<string,int> GetBalance(string name) | |
{ | |
if(name == "Jo") | |
return 1337; | |
return $"Left: Balance not found for user: <{name}>"; | |
} | |
} | |
public class Handler | |
{ | |
private readonly Repository _repo; | |
private readonly HttpAgent _agent; | |
public Handler(Repository repo, HttpAgent agent) | |
{ | |
_repo = repo; | |
_agent = agent; | |
} | |
public async Task<string> GetBalanceReport(int userID) | |
{ | |
var result = | |
_repo | |
.GetName(userID) | |
.Bind<(string name, EitherAsync<string, int> balance)>( | |
name => (name, _agent.GetBalance(name))) | |
//aaand finally something with the results: | |
.Match( | |
tuple => tuple.balance.Match( | |
balance => $"Balance for <{tuple.name}>: <{balance}>", | |
left => left), | |
() => Task.FromResult($"None: User name not found for id <{userID}>")); | |
return await (await result); | |
} | |
} | |
public class EitherOptionPipelines | |
{ | |
[Fact] | |
public async Task EitherOptionAsyncPipelines() | |
{ | |
var handler = new Handler(new Repository(), new HttpAgent()); | |
Assert.Equal("Balance for <Jo>: <1337>", await handler.GetBalanceReport(1)); | |
Assert.Equal("Left: Balance not found for user: <Ruben>", await handler.GetBalanceReport(2)); | |
Assert.Equal("None: User name not found for id <3>", await handler.GetBalanceReport(3)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment