Skip to content

Latest commit

 

History

History
107 lines (82 loc) · 3 KB

README.md

File metadata and controls

107 lines (82 loc) · 3 KB

ResultType & ResultType.Validation

  • NuGet Status

    ResultType ResultType.Validation
    nuget NuGet NuGet
  • Build Status Build Status

ResultType

ResultType implementation in C#

Could be downloaded from NuGet: Install-Package MNie.ResultType

Simple usage:

  • without value
var result = ResultFactory.CreateSuccess();

var error = ResultFactory.CreateFailure<Unit>();
  • with value
var result = ResultFactory.CreateSuccess(true);

var error = ResultFactory.CreateFailure<bool>("error message");
  • chaining results
var result = ResultFactory.CreateSuccess()
  .Bind(fromPreviousSuccess => ResultFactory.CreateSuccess(true));
var result = ResultFactory.CreateSuccess()
  .Bind(() => ResultFactory.CreateSuccess(true));
var result = ResultFactory.CreateSuccess()
  .Bind((fromPreviousSuccess, fromPreviousFailure) => ResultFactory.CreateSuccess(true));
  • mapping result
[HttpGet]
public IActionResult SomeAction() =>
    "test".ToSuccess().Map(Ok, BadRequest);

Bind function accepts Func<TPrevious, TOutput> or Func<TOuput> it depends on you if you want to based on the previous value. There is also an async implementation of Bind with Async postfix. There are also async functions which in fact are boxing result into a Task.

ResultFactory.CreateSuccessAsync
ResultFactory.CreateFailureAsync

ResultType.Validation

ResultType.Validation package provides a simple Rule class to defines Rules which should apply to some objects and as a result returns ResultType. Could be downloaded from NuGet: Install-Package MNie.ResultType.Validation

example usage looks like this:

var rules = new[]
{
    new Rule(() => "name".StartsWith("n"), "name"),
    new Rule(() => "dd".StartsWith("e"), "dd"),
    new Rule(() => "hh".StartsWith("a"), "hh"),
    new Rule(() => "hehe".StartsWith("h"), "hehe"),
};
var result = rules.Apply();

Besides Rule class package provides also a RuleBuilder class. By which you could define predicates based on which Success or Failure would be created.

Sample usage:

class TestObject
{
    public readonly string FieldA;
    public readonly int FieldB;
    
    public TestObject(string fieldA, int fieldB)
    {
        FieldA = fieldA;
        FieldB = fieldB;
    }
}

...

var result = RuleBuilder
                .Build(() => new TestObject("", 5))
                .For(x => x.FieldB, x => x > 10, "greater than 10")
                .For(x => x.FieldB, x => x < 2, "less than 2")
                .Apply();