Olian04 / Recordari

Recordari is a type and structure validation tool for configuration files
MIT License
4 stars 0 forks source link

Expressive error messages #4

Open Olian04 opened 6 years ago

Olian04 commented 6 years ago
const { Record, R } = require('record.js');

const RSettings = Record('Settings', {
  foo: R.Number.Natural, 
  bar: R.Array.Each.String.Either(['a', 'b']), 
  biz: {
    baz: R.Number.Between(0, 8)
  },
  baz: R.or([
    R.String.Length.Max(2),
    R.String.Length.Min(10)
  ]),
  boz: R.and([
    R.Function.Arguments.Length.Exact(2),
    R.Function.Arguments.Each.Matches(/\d$/),
    R.Function.Test(1, 2).Number.Exact(3)
  ]),
  bez: R.and([
    R.Regex.Test('1.1.0').True,
    R.Regex.Test('0.0.0').False
  ])
});

const failRecord = RSettings({
  foo: 5.01, //                     Error: Settings.foo => 5.01 is not a natural number
  bar: ['c'], //                    Error: Settings.bar[0] => 'c' is not in ['a', 'b'] 
  biz: { baz: 1.654, boo: 'd' }, // Error: Settings.biz => Unexpected key 'boo'.
  baz: 'hello', //                  Error: Settings.baz => 'hello'.length is not, less than 3, nor greater than 9
  boz: (a, b, c) => a, //           Error: Settings.boz => Function does not take exacly 2 arguments.
  hello: 'Record.js' //             Error: Settings => Unexpected key 'hello'.
  bez: /^\d+\.\d+\.\d+$/ //         Error: Settings.bez => '0.0.0'.match should be false
});
Olian04 commented 6 years ago

What about this api (asking future me)?

Evaluate(val, constraint, e => 
  throw `${name}.${e.key} => Expected ${e.value} to ${e.not ? 'not' : ''} ${e.message}` 
  // EX: Demo.foo => Expected 3 to be less than or equal to 1
)