Olian04 / Recordari

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

Finish top level api, depends on #9 #17

Closed Olian04 closed 6 years ago

Olian04 commented 6 years ago

The api module should expose 2 things, a function for constructing a new Record, and an object to access the constraint builder.

const { Record, R } = require('record.js');

const RConfig = Record('Config', {
  port: R.Number.Natural,
  env: R.String.Either(['dev', 'prod']),
  loglevel: R.String.Either(['none', 'error', 'warn', 'info', 'debug'])
});

const config = RConfig(require('config.json')); // Should throw if a constraint fails
config.loglevel
config.port
config.env 
Olian04 commented 6 years ago

v1 proposal:

const Record = (type, constraintObject) => (obj) => {
  if(Assert( obj, R.Object.Like(constraintObject) )) {
     throw new TypeError(`Failed to construct a record of type "${type}", object does not comply to the constraints of a ${type} record.`);
  }
  return obj;
}

const RFoo = Record('foo', {
  bar: R.Number
});

const foo_ok = RFoo({
  bar: 1
});

const foo_fail = RFoo({
  bar: '1'
});