Created
May 20, 2024 19:58
-
-
Save helabenkhalfallah/0977966aec44ac9c7cdc2424493484f8 to your computer and use it in GitHub Desktop.
Proxy validation and sanitization
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 validator = { | |
set(obj, prop, value, receiver) { | |
if (prop === "age") { | |
if (!Number.isInteger(value)) { | |
throw new TypeError("The age is not an integer"); | |
} | |
if (value > 200) { | |
throw new RangeError("The age seems invalid"); | |
} | |
} | |
// The default behavior to store the value | |
return Reflect.set(obj, prop, value, receiver); | |
}, | |
}; | |
const person = new Proxy({}, validator); | |
person.age = 100; | |
console.log(person.age); // 100 | |
// person.age = "young"; // Throws an exception | |
// person.age = 300; // Throws an exception |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment