Transform an Archetype So All Properties are Not Required
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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