Proxy design pattern

PUBLISHED ON: Saturday, Sep 17, 2022

Instead of interacting with the target object directly, we'll interact with the Proxy object.

A proxy can be useful to add validation, formatting, notification or debugging.


const person = {
  name: "John Doe",
  age: 42,
  nationality: "American"
};

const personProxy = new Proxy(person, {
  get: (obj, prop) => {
    if (!obj[prop]) {
      console.log(`${prop} doesn't exist!!`);
    } else {
      console.log(`The value of ${prop} is ${Reflect.get(obj, prop)}`);
    }
  },
  set: (obj, prop, value) => {
    if (prop === "age" && typeof value !== "number") {
      console.log(`Invalid value for property age`);
    } else if (prop === "name" && value.length < 2) {
      console.log(`Invalid value for property value`);
    } else {
      console.log(`Changed ${prop} from ${obj[prop]} to ${value}.`);
      Reflect.set(obj, prop, value);
    }
  },
});

console.log(personProxy.name);
personProxy.age = 43; // Changed age from 42 to 43.
personProxy.age = '43'; // Invalid value for property age