javascript / intermediate
Snippet
Data Validation with Proxies
The Proxy object allows you to create a wrapper for another object, which can intercept and redefine fundamental operations for that object, such as property lookup, assignment, and enumeration.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const schema = {set(target, prop, value) {if (prop === 'age') {if (typeof value !== 'number' || value < 0) {throw new TypeError('Age must be a positive number');}}target[prop] = value;return true;}};const user = new Proxy({}, schema);user.age = 25; // Works// user.age = -5; // Throws Error
Breakdown
1
set(target, prop, value) {
A 'trap' for setting a property value on the target object.
2
throw new TypeError(...);
Enforces business logic by preventing invalid data from being saved.
3
target[prop] = value;
Actually performs the assignment if validation passes.
4
new Proxy({}, schema);
Creates the proxy with an empty object as target and the schema as handler.