Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.