0 day streak
javascript / intermediate
Snippet

Input Validation with Proxy

A Proxy object wraps another object and intercepts fundamental operations. In Node.js applications, proxies are excellent for implementing automatic validation or logging whenever an object's properties are modified.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const userSchema = {
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({}, userSchema);
user.age = 25; // Works
user.age = 'invalid'; // Throws TypeError
nodejs
Breakdown
1
set(target, prop, value)
A trap for setting property values, allowing logic to run before the assignment.
2
new Proxy({}, userSchema)
Creates a virtualized version of an empty object governed by the schema handler.
3
return true;
Indicates that the property assignment was successful; returning false throws a TypeError in strict mode.