Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RTTC quick start

RTTC: Quick Start

Want to coerce a value to match a particular type?

var rttc = require('rttc');

rttc.coerce({ firstName: 'string'}, {firstName: 13375055});
// => { firstName: "13375055" }

rttc.coerce({ firstName: 'string'}, {something: 'totally incorrect'});
// => { firstName: "" }
// (when confronted with something totally weird, `.coerce()` returns the "base value" for the type)

Want to throw an Error if a value doesn't match a particular type?

rttc.validateStrict({ firstName: 'string'}, {firstName: 13375055});
// throws error
// (`.validateStrict()` demands a value that is precisely the correct type)

rttc.validateStrict({ firstName: 'string'}, {firstName: '13375055'});
// does not throw

Or if you want to be a little more forgiving:

rttc.validate({ firstName: 'string'}, {something: 'totally incorrect'});
// throws error

rttc.validate({ firstName: 'string'}, {firstName: 45});
// => "45"
// (when confronted with minor differences, `.validate()` coerces as needed to make stuff fit)

Not sure how to build a type schema for use with .coerce() or .validate()? Use .infer() to build one from an example value you've got laying around:

rttc.infer({ firstName: 'Rosella', lastName: 'Graham', friends: ['Valencia', 'Edgar', 'Attis'] });
// => { firstName: 'string',  lastName: 'string', friends: ['string'] }

This special example value is called an exemplar.

Note that when inferring the schema for an array in an exemplar, the array item is considered the pattern. It is used to indicate the expected type of each item in the array. Consequently, if an array in an exemplar has an item, that means it is homogeneous (i.e. all its items have the same schema).

You can use exemplars to specify just about any type-- here's a more advanced schema to show what I mean:

rttc.infer([{ upstream: '===', fieldName: 'photos', files: [{getFile: '->', fileName: 'whatever', numBytes: 34353, meta: '*' }] }]);
// =>
// [
//  {
//    upstream: 'ref',
//    fieldName: 'string',
//    files: [
//      {
//        getFile: 'lamda',
//        fileName: 'string',
//        numBytes: 'number',
//        meta: 'json'
//      }
//    ]
// }
// ]

Note that all of the validation and coercion strategies used in this modules are recursive through the keys of plain old JavaScript objects and the indices of arrays.

More Info

For further information, in-depth reference documentation, and more examples, see http://github.com/node-machine/rttc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment