Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Chain and ChainAsync #77

Merged
merged 4 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 53 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@
</div>

- [Give it a star ⭐!](#give-it-a-star-)
- [Getting Started](#getting-started)
- [Getting Started 🏃](#getting-started-)
- [Single Error](#single-error)
- [This 👇🏽](#this-)
- [Turns into this 👇🏽](#turns-into-this-)
- [This 👇🏽](#this--1)
- [Turns into this 👇🏽](#turns-into-this--1)
- [Multiple Errors](#multiple-errors)
- [A more practical example](#a-more-practical-example)
- [Dropping the exceptions throwing logic](#dropping-the-exceptions-throwing-logic)
- [Usage](#usage)
- [A more practical example 👷](#a-more-practical-example-)
- [Dropping the exceptions throwing logic ✈️](#dropping-the-exceptions-throwing-logic-️)
- [Usage 🛠️](#usage-️)
- [Creating an `ErrorOr<result>`](#creating-an-errororresult)
- [From Value, using implicit conversion](#from-value-using-implicit-conversion)
- [From Value, using `ErrorOrFactory.From`](#from-value-using-errororfactoryfrom)
Expand All @@ -44,21 +44,22 @@
- [`MatchFirst` / `MatchFirstAsync`](#matchfirst--matchfirstasync)
- [`Switch` / `SwitchAsync`](#switch--switchasync)
- [`SwitchFirst` / `SwitchFirstAsync`](#switchfirst--switchfirstasync)
- [`Chain` / `ChainAsync`](#chain--chainasync)
- [Error Types](#error-types)
- [Built-in Error Types](#built-in-error-types)
- [Custom error types](#custom-error-types)
- [Why would I want to categorize my errors?](#why-would-i-want-to-categorize-my-errors)
- [Built in result types](#built-in-result-types)
- [How Is This Different From `OneOf<T0, T1>` or `FluentResults`?](#how-is-this-different-from-oneoft0-t1-or-fluentresults)
- [Contribution](#contribution)
- [Credits](#credits)
- [License](#license)
- [How Is This Different From `OneOf<T0, T1>` or `FluentResults`? 🤔](#how-is-this-different-from-oneoft0-t1-or-fluentresults-)
- [Contribution 🤲](#contribution-)
- [Credits 🙏](#credits-)
- [License 🪪](#license-)

# Give it a star ⭐!

Loving it? Show your support by giving this project a star!

# Getting Started
# Getting Started 🏃

## Single Error

Expand Down Expand Up @@ -197,7 +198,7 @@ public async Task<ErrorOr<User>> CreateUserAsync(string name)
}
```

# A more practical example
# A more practical example 👷

```csharp
[HttpGet("{id:guid}")]
Expand Down Expand Up @@ -247,7 +248,7 @@ return createUserResult.MatchFirst(
error => error is Errors.User.DuplicateEmail ? Conflict() : InternalServerError());
```

# Dropping the exceptions throwing logic
# Dropping the exceptions throwing logic ✈️

You have validation logic such as `MediatR` behaviors, you can drop the exceptions throwing logic and simply return a list of errors from the pipeline behavior

Expand Down Expand Up @@ -303,7 +304,7 @@ public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TReques
}
```

# Usage
# Usage 🛠️

## Creating an `ErrorOr<result>`

Expand Down Expand Up @@ -509,6 +510,42 @@ await errorOrString.SwitchFirstAsync(
firstError => { Console.WriteLine(firstError.Description); return Task.CompletedTask; });
```

### `Chain` / `ChainAsync`

Multiple methods that return `ErrorOr<T>` can be chained as follows

```csharp
static ErrorOr<string> ConvertToString(int num) => num.ToString();
static ErrorOr<int> ConvertToInt(string str) => int.Parse(str);

ErrorOr<string> errorOrString = "5";

ErrorOr<string> result = errorOrString
.Chain(str => ConvertToInt(str))
.Chain(num => ConvertToString(num))
.Chain(str => ConvertToInt(str))
.Chain(num => ConvertToString(num))
.Chain(str => ConvertToInt(str))
.Chain(num => ConvertToString(num));
```

```csharp
static Task<ErrorOr<string>> ConvertToString(int num) => Task.FromResult(ErrorOrFactory.From(num.ToString()));
static Task<ErrorOr<int>> ConvertToInt(string str) => Task.FromResult(ErrorOrFactory.From(int.Parse(str)));

ErrorOr<string> errorOrString = "5";

ErrorOr<string> result = await errorOrString
.ChainAsync(str => ConvertToInt(str))
.ChainAsync(num => ConvertToString(num))
.ChainAsync(str => ConvertToInt(str))
.ChainAsync(num => ConvertToString(num))
.ChainAsync(str => ConvertToInt(str))
.ChainAsync(num => ConvertToString(num));
```

If any of the methods return an error, the chain will be broken and the error will be returned.

## Error Types

### Built-in Error Types
Expand Down Expand Up @@ -599,19 +636,19 @@ ErrorOr<Deleted> DeleteUser(Guid id)
}
```

# How Is This Different From `OneOf<T0, T1>` or `FluentResults`?
# How Is This Different From `OneOf<T0, T1>` or `FluentResults`? 🤔

It's similar to the others, just aims to be more intuitive and fluent.
If you find yourself typing `OneOf<User, DomainError>` or `Result.Fail<User>("failure")` again and again, you might enjoy the fluent API of `ErrorOr<User>` (and it's also faster).

# Contribution
# Contribution 🤲

If you have any questions, comments, or suggestions, please open an issue or create a pull request 🙂

# Credits
# Credits 🙏

- [OneOf](https://github.com/mcintyre321/OneOf/tree/master/OneOf) - An awesome library which provides F# style discriminated unions behavior for C#

# License
# License 🪪

This project is licensed under the terms of the [MIT](https://github.com/mantinband/error-or/blob/main/LICENSE) license.
39 changes: 27 additions & 12 deletions src/ErrorOr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,21 +259,36 @@ public async Task<TResult> MatchFirstAsync<TResult>(Func<TValue, Task<TResult>>

return await onValue(Value).ConfigureAwait(false);
}
}

/// <summary>
/// Provides utility methods for creating instances of <see ref="ErrorOr{T}"/>.
/// </summary>
public static class ErrorOr
{
/// <summary>
/// Creates an <see ref="ErrorOr{TValue}"/> instance from a value.
/// If the state is a value, the provided function <paramref name="onValue"/> is executed and its result is returned.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="value">The value from which to create an ErrorOr instance.</param>
/// <returns>An <see ref="ErrorOr{TValue}"/> instance containing the specified value.</returns>
public static ErrorOr<TValue> From<TValue>(TValue value)
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="onValue">The function to execute if the state is a value.</param>
/// <returns>The result from calling <paramref name="onValue"/> if state is value; otherwise the original <see cref="Errors"/>.</returns>
public ErrorOr<TResult> Chain<TResult>(Func<TValue, ErrorOr<TResult>> onValue)
{
return value;
if (IsError)
{
return Errors;
}

return onValue(Value);
}

/// <summary>
/// If the state is a value, the provided function <paramref name="onValue"/> is executed asynchronously and its result is returned.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="onValue">The function to execute if the state is a value.</param>
/// <returns>The result from calling <paramref name="onValue"/> if state is value; otherwise the original <see cref="Errors"/>.</returns>
public async Task<ErrorOr<TResult>> ChainAsync<TResult>(Func<TValue, Task<ErrorOr<TResult>>> onValue)
{
if (IsError)
{
return Errors;
}

return await onValue(Value).ConfigureAwait(false);
}
}
19 changes: 19 additions & 0 deletions src/ErrorOrExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace ErrorOr;

public static class ErrorOrExtensions
{
/// <summary>
/// If the state of <paramref name="errorOr"/> is a value, the provided function <paramref name="onValue"/> is executed asynchronously and its result is returned.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <typeparam name="TNextResult">The type of the next result.</typeparam>
/// <param name="errorOr">The error.</param>
/// <param name="onValue">The function to execute if the state is a value.</param>
/// <returns>The result from calling <paramref name="onValue"/> if state is value; otherwise the original errors.</returns>
public static async Task<ErrorOr<TNextResult>> ChainAsync<TResult, TNextResult>(this Task<ErrorOr<TResult>> errorOr, Func<TResult, Task<ErrorOr<TNextResult>>> onValue)
amantinband marked this conversation as resolved.
Show resolved Hide resolved
{
var result = await errorOr;

return await result.ChainAsync(onValue).ConfigureAwait(false);
}
}
51 changes: 51 additions & 0 deletions tests/ErrorOr.ChainAsyncTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using ErrorOr;
using FluentAssertions;

namespace Tests;

public class ChainAsyncTests
{
record Person(string Name);

[Fact]
public async Task ChainErrorOrsAsync_WhenStateIsValue_ShouldInvokeNextInChain()
{
// Arrange
ErrorOr<Person> errorOrPerson = new Person("Amichai");

static Task<ErrorOr<string>> GetNameAsync(Person person) => Task.FromResult(ErrorOrFactory.From(person.Name));
static Task<ErrorOr<Person>> CreatePersonFromNameAsync(string name) => Task.FromResult(ErrorOrFactory.From(new Person(name)));

// Act
var result = await errorOrPerson
.ChainAsync(person => GetNameAsync(person))
.ChainAsync(name => CreatePersonFromNameAsync(name))
.ChainAsync(person => GetNameAsync(person))
.ChainAsync(name => CreatePersonFromNameAsync(name));

// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(errorOrPerson.Value);
}

[Fact]
public async Task ChainErrorOrsAsync_WhenStateIsError_ShouldReturnErrors()
{
// Arrange
ErrorOr<Person> errorOrPerson = Error.NotFound();

static Task<ErrorOr<string>> GetNameAsync(Person person) => Task.FromResult(ErrorOrFactory.From(person.Name));
static Task<ErrorOr<Person>> CreatePersonFromNameAsync(string name) => Task.FromResult(ErrorOrFactory.From(new Person(name)));

// Act
var result = await errorOrPerson
.ChainAsync(person => GetNameAsync(person))
.ChainAsync(name => CreatePersonFromNameAsync(name))
.ChainAsync(person => GetNameAsync(person))
.ChainAsync(name => CreatePersonFromNameAsync(name));

// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().BeEquivalentTo(Error.NotFound());
}
}
47 changes: 47 additions & 0 deletions tests/ErrorOr.ChainTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using ErrorOr;
using FluentAssertions;

namespace Tests;

public class ChainTests
{
record Person(string Name);

[Fact]
public void ChainErrorOrs_WhenHasValue_ShouldInvokeNextInChain()
{
// Arrange
ErrorOr<Person> errorOrPerson = new Person("Amichai");

static ErrorOr<string> GetName(Person person) => person.Name;
static ErrorOr<Person> CreatePersonFromName(string name) => new Person(name);

// Act
ErrorOr<Person> result = errorOrPerson
.Chain(person => GetName(person))
.Chain(name => CreatePersonFromName(name));

// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeEquivalentTo(errorOrPerson.Value);
}

[Fact]
public void ChainErrorOrs_WhenHasError_ShouldReturnErrors()
{
// Arrange
ErrorOr<Person> errorOrPerson = Error.NotFound();

static ErrorOr<string> GetName(Person person) => person.Name;
static ErrorOr<Person> CreatePersonFromName(string name) => new Person(name);

// Act
ErrorOr<Person> result = errorOrPerson
.Chain(person => GetName(person))
.Chain(name => CreatePersonFromName(name));

// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().BeEquivalentTo(Error.NotFound());
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading
Loading