Serializable, validated, and observable data layer for modern JS applications
npm install type-r2javascript
import { define, Record } from 'type-r'
// Define email attribute type with encapsulated validation check.
const Email = String.has.check( x => x! || x.indexOf( '@' ) >= 0, 'Invalid email' );
@define class User extends Record {
static attributes = {
name : String.isRequired, // should not be empty for the record to be valid.
email : Email.isRequired
}
}
@define class Message extends Record {
static attributes = {
created : Date // = new Date()
author : User, // aggregated User record.
to : User.Collection, // aggregating collection of users
subject : '',
body : ''
}
}
const msg = new Message();
assert( !msg.isValid() ); // Is not valid because msg.author has empty attributes
// Listen for the changes in aggregation tree...
msg.on( 'change', () => console.log( 'change!!!' ) );
msg.transaction( () => { // Prepare to make the sequence of changes on msg
msg.author.name = 'John Dee'; // No 'change' event yet as we're in the transaction.
msg.author.email = 'dee@void.com';
assert( msg.isValid() ); // Now msg is valid as all of its attributes are valid.
}); // Got single 'change!!!' message in the console.
`
Documentation
Installation and requirements
Is packed as UMD and ES6 module. No peer dependencies are required.
npm install type-r --save-dev`