What is a Proxy?
A Proxy wraps an object and lets you intercept operations like property access, assignment, and deletion via handler functions (traps).
const target = { name: "Alice", age: 30 };
const handler = {
get(obj, prop) {
console.log("Getting " + prop);
return obj[prop];
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.name);
console.log(proxy.age);
Try it Yourself โ
get and set Traps
The get trap intercepts property reads. The set trap intercepts property writes โ you can validate or transform values.
const validator = {
set(obj, prop, value) {
if (prop === "age") {
if (typeof value !== "number" || value < 0) {
throw new Error("Invalid age");
}
}
obj[prop] = value;
return true;
}
};
const user = new Proxy({}, validator);
user.name = "Bob";
user.age = 25;
console.log(user.age);
try {
user.age = -5;
} catch (err) {
console.error(err.message);
}
Try it Yourself โ
Validation with Proxy
Use proxies to enforce data constraints, log changes, or provide default values for missing properties.
function createValidatedObject(schema) {
return new Proxy({}, {
set(obj, prop, value) {
if (schema[prop]) {
const rules = schema[prop];
if (rules.type && typeof value !== rules.type) {
throw new Error(prop + " must be " + rules.type);
}
if (rules.min && value < rules.min) {
throw new Error(prop + " minimum is " + rules.min);
}
}
obj[prop] = value;
return true;
}
});
}
const product = createValidatedObject({
price: { type: "number", min: 0 },
stock: { type: "number", min: 0 }
});
product.price = 29.99;
product.stock = 100;
console.log(product.price, product.stock);
Try it Yourself โ