Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Created July 29, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digitalconceptvisuals/374f178c6c9ae09fa7248e8a4f8f7c49 to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/374f178c6c9ae09fa7248e8a4f8f7c49 to your computer and use it in GitHub Desktop.
// Simple object
let person = {
id: 0,
name: "default",
}
// There is no validation if object is used directly
person.id = "Eich"; // We would like it to be positive integer
person.name = 3.14; // Name should ideally be non blank string
console.log(person);
// Let's setup Proxy handler with validations
const handler = {
set(object, property, value, receiver) {
// id should be positive integer
if (property == "id") {
if (typeof value != 'number' || value < 0)
throw "id should be a positive number";
}
// name should be a non blank string
if (property == "name") {
if (typeof value != 'string' || value.trim() == "")
throw "name should be a non blank string";
}
// Passed all validations, so assign to real object
return Reflect.set(object, property, value, receiver);
}
}
// Use a Proxy to person object
const PersonProxy = new Proxy(person, handler);
// These should give errors
PersonProxy.id = "Brendan";
PersonProxy.name = 1;
console.log(PersonProxy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment