Created
January 13, 2018 01:22
-
-
Save vkarpov15/32abd9f72dfb2ba1558e9e6a1060c768 to your computer and use it in GitHub Desktop.
Virtual Types with Archetype
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'); | |
const UserBaseType = new Archetype({ | |
name: { | |
first: { | |
$type: 'string', | |
$required: true | |
}, | |
last: { | |
$type: 'string', | |
$required: true | |
} | |
} | |
}).compile('UserBaseType'); | |
// `UserBaseType` is a plain JS class, so you can `extends` | |
class UserType extends UserBaseType { | |
// Plain old ES6 getters and setters. This gets you the full name | |
get fullName() { | |
return `${this.name.first} ${this.name.last}`; | |
} | |
// You can also create `firstName` and `lastName` as aliases for | |
// `name.first` and `name.last` | |
get firstName() { | |
return this.name.first; | |
} | |
set firstName(v) { | |
this.name.first = v; | |
} | |
get lastName() { | |
return this.name.last; | |
} | |
set lastName(v) { | |
this.name.last = v; | |
} | |
} | |
const user = new UserType({ name: { first: 'Axl', last: 'Rose' } }); | |
console.log(user.fullName); // 'Axl Rose' | |
console.log(user.lastName); // 'Rose' | |
user.firstName = 'William'; | |
console.log(user.name.first); // 'William' | |
console.log(user.fullName); // 'William Rose' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment