busypeoples / spected

Validation library
MIT License
703 stars 32 forks source link

Data coercions #88

Open fgarcia opened 7 years ago

fgarcia commented 7 years ago

Is there any plan for adding field coercion along the validations?

busypeoples commented 7 years ago

We could think about adding this feature. Thanks for the input!

fgarcia commented 7 years ago

Great! I absolutely like your functional approach. Validations is a great use case for FP.

It is also clear that one could build a layer on top to build objects returning an Either monad where the Left value is a result from spected. However the cut and focus on validations is great. People get the best of FP without having to understand FP.

I can build more abstractions on top, but I am not so sure about coercions. I have the feeling that the most elegant solution is a combination of validation and coercions, but I can't figure out a clean/simple way to do it.

busypeoples commented 7 years ago

Thank you very much for the feedback! Highly appreciated. Regarding coercions, yes this needs some thinking for sure.

fgarcia commented 7 years ago

If it helps, this is my line of thought:


const normalizeString = (rules, {default}) => (value, f) => {
  let before = value || 'anonymous'

  let result = f(before)
  // ignoring failed case 
  let after = _.toLowerCase(value)

  return ... // after? custom struct? monad?
}

const validationRules = {
  name: normalizeString([
    [ isGreaterThan(5),
      `Minimum Name length of 6 is required.`
    ],
  ]),
}

After doing the coercion with normalizeString I noticed that:

  1. Coercions / Transformations might be done before AND after the validation
  2. It must be a higher order function
  3. The Either monad seems a good option, but using monads might put off many people
busypeoples commented 7 years ago

Good points. Will also think about how we can makes this efficient. Regarding Either, agree, if we can avoid exposing it in user land would be helpful for adoption.

fgarcia commented 7 years ago

I must retract myself in one of the points. Now I believe coercions must be done before validation. Any modification after validation seems to me now awfully conflicting (like setting invalid values)