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

feat: Add OrFailIf extension method #221

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
43 changes: 43 additions & 0 deletions src/FluentResults.Test/OrFailIfTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Linq;
using FluentAssertions;
using FluentResults.Extensions;
using Xunit;

namespace FluentResults.Test
{
public class OrFailIfTests
{
[Fact]
public void Does_not_evaluate_if_the_previous_statement_has_failed()
{
var result = Result.FailIf(true, "Error 1")
.OrFailIf(true, "Error 2");

result.IsFailed.Should().BeTrue();
result.Errors.Select(s => s.Message)
.Should()
.BeEquivalentTo("Error 1");
}

[Fact]
public void Evaluates_if_the_previous_statement_has_succeeded()
{
var result = Result.FailIf(false, "Error 1")
.OrFailIf(true, "Error 2");

result.IsFailed.Should().BeTrue();
result.Errors.Select(s => s.Message)
.Should()
.BeEquivalentTo("Error 2");
}

[Fact]
public void Succeeds_if_all_statements_have_succeeded()
{
var result = Result.FailIf(false, "Error 1")
.OrFailIf(false, "Error 2");

result.IsSuccess.Should().BeTrue();
}
}
}
17 changes: 17 additions & 0 deletions src/FluentResults/Extensions/ResultExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -329,5 +329,22 @@ public static async Task<Result<TValue>> ToResult<TValue>(this ValueTask<Result>
var result = await resultTask;
return result.ToResult(value);
}

/// <summary>
/// Create a success/failed result depending on the parameter isFailure
/// </summary>
/// <param name="source">The previous result</param>
/// <param name="isFailure">The condition to check if the result should fail</param>
/// <param name="error">The error message</param>
/// <returns>The previous result if it is already failed or a new result</returns>
public static Result OrFailIf(this Result source, bool isFailure, string error)
{
if (source.IsFailed)
{
return source;
}

return isFailure ? Result.Fail(error) : source;
}
}
}