Skip to content

Instantly share code, notes, and snippets.

@vkarpov15
Created January 5, 2018 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkarpov15/6c49c0bc5ed0eab42633645bf03e8fa7 to your computer and use it in GitHub Desktop.
Save vkarpov15/6c49c0bc5ed0eab42633645bf03e8fa7 to your computer and use it in GitHub Desktop.
Transform an Archetype So All Properties are Not Required
const Archetype = require('archetype');
// `UserType` has 3 required properties
const UserType = new Archetype({
name: { $type: 'string', $required: true },
email: { $type: 'string', $required: true },
age: { $type: 'number', $required: true }
}).compile('UserType');
// But what if we want an `update()` function that updates a user?
// The `update()` function should take an argument that is an object
// that looks like `UserType`, but none of the properties are required
class User extends UserType {
update(user) {
// `UserUpdateType` is the modified `UserType` that you'll see below
user = new UserUpdateType(user);
return Object.assign(this, user);
}
}
const UserUpdateType = UserType.
transform((path, props) => {
// Prints for each path in `UserType`:
// name { '$type': 'string', '$required': true }
// email { '$type': 'string', '$required': true }
// age { '$type': 'number', '$required': true }
console.log(path, props);
delete props.$required;
return props;
}).
compile('UserUpdateType');
const user = new User({ name: 'Val', email: 'test@test.com', age: '28' });
// Archetype will cast `age` to a number if it is present
user.update({ age: '29'});
console.log(user);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment