-
-
Save digitalconceptvisuals/374f178c6c9ae09fa7248e8a4f8f7c49 to your computer and use it in GitHub Desktop.
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
// 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