Created
May 31, 2021 15:03
-
-
Save lilbond/e411cad569d0ce01d906a893a24c2655 to your computer and use it in GitHub Desktop.
Simple base class to quickly and somewhat safely create DTO/Model etc.
This file contains hidden or 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
| class Dataclass { | |
| constructor(props, defaults, required) { | |
| if (props) { | |
| for (const key in props) { | |
| if (Object.hasOwnProperty.call(props, key)) { | |
| this[key] = props[key]; | |
| } | |
| } | |
| } | |
| if (defaults) { | |
| for (const key in defaults) { | |
| if (Object.hasOwnProperty.call(defaults, key)) { | |
| this[key] = defaults[key]; | |
| } | |
| } | |
| } | |
| if (required) { | |
| for (const key in required) { | |
| if (Object.hasOwnProperty.call(required, key)) { | |
| if (!this[required[key]]) { | |
| throw new Error(`{${required[key]}} is required.`) | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| // From some rest service | |
| const props = { | |
| name: 'Mickey Mouse', | |
| email: '[email protected]', | |
| age: 45 | |
| } | |
| // Simple data transfer class | |
| class Person extends Dataclass { | |
| static defaults = { | |
| active: false | |
| } | |
| static required = ['age']; | |
| constructor(props) { | |
| super(props, Person.defaults, Person.required) | |
| } | |
| } | |
| const mickey = new Person(props); | |
| console.log(mickey) | |
| /** | |
| * Output | |
| * ------- | |
| * | |
| Person { name: 'Mickey Mouse', | |
| email: '[email protected]', | |
| age: 45, | |
| active: false } | |
| * | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment