DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 23: Proxy

Have you ever wished you could intercept and modify object behaviour in JavaScript without changing its original structure?. πŸ¦Έβ€β™‚οΈ That's where the Proxy object comes to the rescue!

πŸ•΅οΈβ€β™‚οΈ Proxy Object

A Proxy object in JavaScript allows you to define custom behaviour for fundamental operations performed on an object. These operations include property access, assignment, function invocation, and more. Essentially, a Proxy sits between your code and the object, enabling you to intercept and control its interactions.

πŸ“ Data Validation for a User Object

Imagine you're building a user authentication system for a web application. You want to ensure that the user data adheres to certain validation rules before it's stored or updated. Instead of scattering validation checks throughout your code, you can use a Proxy to centralize and streamline this process.

const userValidator = {
  set(target, property, value) {
    if (property === 'username') {
      if (typeof value !== 'string' || value.length < 5) {
        throw new Error('Username must be a string of at least 5 characters');
      }
    } else if (property === 'email') {
      if (!value.includes('@')) {
        throw new Error('Invalid email address');
      }
    }

    target[property] = value;
    return true;
  },
};

const user = new Proxy({}, userValidator);

try {
  user.email = 'johnexample.com'; // This will throw an error
} catch (error) {
  console.error(error.message); // Output: Invalid email address
}

user.email = 'john@example.com'; // No error, email is valid

try {
  user.age = 15; // This will throw an error
} catch (error) {
  console.error(error.message); // Output: Invalid age
}
user.age = 25; // No error, age is valid

Enter fullscreen mode Exit fullscreen mode

Here the userValidator object is a Proxy that intercepts property assignments and validates the data before allowing the assignment to occur. If the validation criteria aren't met, it throws an error.

πŸ› οΈ Use Cases of Proxies

  • Logging and Debugging: You can use Proxies to log property access, assignments, and function invocations for debugging purposes.

  • Caching: Implement a caching mechanism by intercepting property accesses and storing values to avoid recalculating them.

  • Immutable Objects: Proxies can be used to create objects with read-only properties, preventing accidental modifications.

Top comments (0)