Created
March 2, 2022 07:31
-
-
Save osorionicolas/f6e2a89d74e8cc20d3381bc82bb94dc2 to your computer and use it in GitHub Desktop.
Proxy validation
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
| const userValidator = { | |
| set(object, prop, value) { | |
| const validProps = ['name', 'email']; | |
| if(!validProps.includes(prop)) { | |
| throw new Error(`Can't set ${prop}`); | |
| } else { | |
| object[prop] = value; | |
| return true; | |
| } | |
| }, | |
| }; | |
| class User { | |
| constructor({ name, email }) { | |
| this.name = name; | |
| this.email = email; | |
| return new Proxy(this, userValidator); | |
| } | |
| } | |
| const user = new User({ name: 'Sifat', email: 'sifat@gmail.com' }); | |
| user.password = '12345678'; | |
| // output: Can't set password |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment