lfr / FSharp.Domain.Validation

Designing with types requires a lot of code - this library fixes that
MIT License
143 stars 7 forks source link

keeping the context of the error and a list #2

Closed simonmcconnell closed 4 years ago

simonmcconnell commented 4 years ago

is there an idiomatic way to to get a list of errors from the validation with the context ala FsToolkit.ErrorHandling's Result.tryCreate as per the validation examples?

let create thing comment someNumber = 
    { Thing = thing; Comment = comment; SomeNumber = someNumber }

let validate thing comment someNumber =
    create
    <!^> Block.validate thing
    <*^> Text.optional comment
    <*^> Text.optional someNumber

will give you Error: [[FirstCharacterInvalid '-']; [FirstCharacterInvalid '-']; [NotAnInt32]]

whereas if we use Result.tryCreate and the validation operators we get:

let validate thing comment someNumber = 
    create
    <!^> Result.tryCreate "Thing" thing
    <*^> Result.tryCreate "Comment" comment
    <*^> Result.tryCreate "SomeNumber" someNumber

Error
  [("Thing", "first characters must be a letter or underscore");
   ("Comment", "first character must be a letter or underscore");
   ("SomeNumber", "not a valid integer")]

The cleanliness of the result CE while accruing errors and their context is the dream.

simonmcconnell commented 4 years ago

This does something similar.

let validateWithContext ctx =
    Block.validate
    >> Result.mapError (fun errors ->
        ctx, errors)

let validateTextOptionWithContext<'block when 'block :> TextBlock> ctx =
    Text.optional<'block>
    >> Result.mapError (fun errors ->
        ctx, errors)

let validatethese thing comment someNumber =
    create
    <!^> validateWithContext "Thing" thing
    <*^> validateTextOptionWithContext "Comment" comment
    <*^> validateTextOptionWithContext "SomeNumber" someNumber
lfr commented 4 years ago

Indeed @simonmcconnell, that's what I end up doing, but maybe this should be added to the API as I'm guessing everyone is going to be writing similar code