public async Task ElTestoAsync() { var request = new SomeOperationRequest(); var validateApiKey = GetApiKey().ToValidation(new ValidationFailure("ApiKey", "API Key is missing in headers")); var v = from v1 in validateApiKey from v2 in Validate(request) select v1 + v2; var appCode = from key in v.ToOption() from code in GetAppCode(key) select code; TryAsync <Result <SomeOperationResult> > bloo = from req in TryAsync(request) from code in appCode.ToTryAsync() select StartPaymentAsync(req, code); string message = await bloo.Match( Succ : tryRes => tryRes.Match( Succ: payRes => $"Payment succeeded! PaymentID = {payRes.PaymentId}", Fail: ex => ex.Message), Fail : ex => ex.Message); message.Should().Contain("42"); }
public async Task Handle(DocumentSentForApprovalEventDto notification, CancellationToken cancellationToken) { TryAsync <Unit> handle = async() => await _updateDocumentStatus(notification.Id, DocumentStatus.WaitingForApproval.ToString()).ToUnit(); await handle.Match( Succ : u => { }, Fail : ex => _logger.LogError($"Error while handling {nameof(DocumentSentForApprovalEventDto)}: {ex}")); }
public async Task Handle(DocumentUpdatedEventDto notification, CancellationToken cancellationToken) { TryAsync <Unit> handle = async() => await _updateDocument(notification.Id, notification.Number, notification.Description).ToUnit(); await handle.Match( Succ : u => { }, Fail : ex => _logger.LogError($"Error while handling {nameof(DocumentUpdatedEventDto)}: {ex}")); }
public async Task Handle(UserCreatedEventDto notification, CancellationToken cancellationToken) { TryAsync <Unit> handle = async() => await _addUser(notification.Id, notification.Email, notification.FirebaseId) .ToUnit(); await handle.Match( Succ : _ => { }, Fail : ex => _logger.LogError($"Error while handling {nameof(UserCreatedEventDto)}: {ex}")); }
public async Task Handle(FileAddedEventDto notification, CancellationToken cancellationToken) { TryAsync <Unit> handle = async() => await _addFile(notification.FileId, notification.Id, notification.FileName, notification.FileDescription).ToUnit(); await handle.Match( Succ : u => { }, Fail : ex => _logger.LogError($"Error while handling {nameof(FileAddedEventDto)}: {ex}")); }
public async Task Handle(DocumentApprovedEventDto notification, CancellationToken cancellationToken) { TryAsync <Unit> handle = async() => await _approveDocument(notification.Id, DocumentStatus.Approved.ToString(), notification.Comment) .ToUnit(); await handle.Match( Succ : u => { }, Fail : ex => _logger.LogError($"Error while handling {nameof(DocumentApprovedEventDto)}: {ex}")); }
public async Task <IActionResult> Get() { TryAsync <Lst <Contract.DTO.Chat.Channel> > svcResult = async() => await _chatService.GetAllChannels(); var result = svcResult.Match <Lst <Contract.DTO.Chat.Channel>, IActionResult>( Succ: model => Ok(model.Select(p => p.Name).ToList()), Fail: ex => StatusCode(500, ex) ); return(await result); }
public async Task <IActionResult> Post([FromBody] Channel channel) { var model = _mapper.Map <Channel, Contract.DTO.Chat.Channel>(channel); TryAsync <Unit> svcResult = async() => await _chatService.AddChannel(model); var result = svcResult.Match <Unit, IActionResult>( Succ: unit => NoContent(), Fail: ex => StatusCode(500, ex) ); return(await result); }
private OptionAsync <Config> LoadAkkaConfig() { TryAsync <Config> tryLoadAkkaConfig = async() => ConfigurationFactory.ParseString(await File.ReadAllTextAsync("hocon.txt")); return(tryLoadAkkaConfig.Match( akkaConfig => akkaConfig, ex => { _logger.LogError("Failed to load akka config"); return (Config)null; })); }
public async Task <IActionResult> Post([FromBody] Message message, int channelId) { message.ChannelId = channelId; var model = _mapper.Map <Message, Contract.DTO.Chat.Message>(message); TryAsync <Unit> svcResult = async() => await _chatService.AddMessage(model); var result = svcResult.Match <Unit, IActionResult>( Succ: unit => NoContent(), Fail: ex => StatusCode(500, ex) ); return(await result); }
public async Task <IActionResult> Get(int channelId) { TryAsync <Lst <Contract.DTO.Chat.Message> > svcResult = async() => await _chatService.GetAllMessagesInChannel(channelId); var result = svcResult.Match <Lst <Contract.DTO.Chat.Message>, IActionResult>( Succ: model => { var messages = model.Select(p => p.Content).ToList(); return(Ok(messages)); }, Fail: ex => StatusCode(500, ex) ); return(await result); }
public static Task <Either <L, A> > ToEither <A, L>(this TryAsync <A> self, Func <Exception, L> Fail) => self.Match( Succ: v => Either <L, A> .Right(v), Fail: x => Either <L, A> .Left(Fail(x)));
public static Task <Either <Exception, A> > ToEither <A>(this TryAsync <A> self) => self.Match( Succ: v => Either <Exception, A> .Right(v), Fail: x => Either <Exception, A> .Left(x));
public static Task <OptionUnsafe <A> > ToOptionUnsafe <A>(this TryAsync <A> self) => self.Match( Succ: v => OptionUnsafe <A> .Some(v), Fail: _ => OptionUnsafe <A> .None);
public static Task <Validation <FAIL, A> > ToValidation <A, FAIL>(this TryAsync <A> self, Func <Exception, FAIL> Fail) => self.Match( Succ: v => Success <FAIL, A>(v), Fail: e => Fail <FAIL, A>(Fail(e)));
public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> self, Func <T, IActionResult> succ = null, Func <Exception, IActionResult> fail = null) => self.Match(Succ: succ ?? GetGenericSuccessResult, Fail: fail ?? GetGenericErrorResult);
/// <summary> /// Success case is converted to 200 OK. /// Exception is converted to 500 Server Error. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="try"></param> /// <returns></returns> public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @try) => @try.Match(Ok, ServerError);
public static Task <R> match <T, R>(TryAsync <T> self, Func <T, R> Succ, R Fail) => self.Match(Succ, Fail);
/// <summary> /// Pattern matches the two possible states of the TryAsync computation /// </summary> /// <typeparam name="T">Type of the bound value</typeparam> /// <param name="self">TryAsync computation</param> /// <param name="Succ">Delegate to invoke if the TryAsync computation completes successfully</param> /// <param name="Fail">Delegate to invoke if the TryAsync computation fails</param> public static Task <Unit> match <T>(TryAsync <T> self, Action <T> Succ, Action <Exception> Fail) => self.Match(Succ, Fail);
public TryAsync <B> Map(TryAsync <A> ma, Func <A, B> f) => () => ma.Match( Succ: x => new Result <B>(f(x)), Fail: e => new Result <B>(e));
/// <summary> /// Converts a <see cref="TryAsync{A}"/> to an <see cref="IActionResult"/>. /// Default success case conversion will convert units to NoContent and all other values to Ok. /// Default failure case conversion will convert exceptions to an InternalServerError. /// </summary> /// <typeparam name="A">The <see cref="TryAsync{A}"/> parameter type.</typeparam> /// <param name="this">The <see cref="TryAsync{A}"/> to convert to an <see cref="IActionResult"/>.</param> /// <param name="Succ">Optionally, a custom conversion for the success case.</param> /// <param name="Fail">Optionally, a custom conversion for the failure case.</param> /// <returns>An <see cref="IActionResult"/> which can be returned from a controller.</returns> public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @this, Func <T, IActionResult> Succ = null, Func <Exception, IActionResult> Fail = null) => @this.Match(Succ: Succ ?? GetGenericSuccessResult, Fail: Fail ?? GetGenericErrorResult);
public static Task <Validation <Exception, A> > ToValidation <A>(this TryAsync <A> self) => self.Match( Succ: v => Success <Exception, A>(v), Fail: e => Fail <Exception, A>(e));
/// <summary> /// By default, Success case is converted to 200 OK and an Exception is converted to 500 Server Error. /// Optionally, provide mapping functions for Success and Exception. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="try"></param> /// <param name="success"></param> /// <param name="fail"></param> /// <returns></returns> public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @try, Func <T, IActionResult> success = null, Func <Exception, IActionResult> fail = null) => @try.Match(success ?? Ok, fail ?? ServerError);
public static Task <IEnumerable <A> > AsEnumerable <A>(this TryAsync <A> self) => self.Match( Succ: v => new A[1] { v }.AsEnumerable(), Fail: x => new A[0].AsEnumerable());
public static Task <Seq <A> > AsEnumerable <A>(this TryAsync <A> self) => self.Match( Succ: v => v.Cons(Empty), Fail: x => Empty);
public Task <Unit> Fail(Action <Exception> f) => value.Match(succHandler, f);
public static Task <string> AsString <A>(this TryAsync <A> self) => self.Match( Succ: v => isnull(v) ? "Succ(null)" : $"Succ({v})", Fail: ex => $"Fail({ex.Message})");
public Task <B> Fail(Func <Exception, B> f) => value.Match(succHandler, f);
public TryAsync <B> BiMap(TryAsync <A> ma, Func <A, B> fa, Func <Unit, B> fb) => () => ma.Match( Succ: x => new Result <B>(fa(x)), Fail: _ => new Result <B>(fb(unit)));
/// <summary> /// By default, Success case is converted to 200 OK and an Exception is converted to 500 Server Error. /// /// Optional: provide mapping function for Success. /// Optional: provide action for Exception logging. Returns 500 Status Code with empty body. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="try"></param> /// <param name="success"></param> /// <param name="fail"></param> /// <returns></returns> public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @try, Func <T, IActionResult> success = null, Action <Exception> fail = null) => @try.Match(success ?? Ok, Fail: e => ServerErrorWithLogging(e, fail));