Skip to content

Instantly share code, notes, and snippets.

@osorionicolas
Created March 2, 2022 07:31
Show Gist options
  • Select an option

  • Save osorionicolas/f6e2a89d74e8cc20d3381bc82bb94dc2 to your computer and use it in GitHub Desktop.

Select an option

Save osorionicolas/f6e2a89d74e8cc20d3381bc82bb94dc2 to your computer and use it in GitHub Desktop.
Proxy validation
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