A Gentle Introduction To Proxy In JavaScript
(Part-1)

A Gentle Introduction To Proxy In JavaScript (Part-1)

·

3 min read

Hi Everyone,

Today I want to talk about the proxy object in Javascript. It is an advanced topic and also is asked in Coding Interviews. Without any further ado let's start.

Proxy is a wrapper around an object, that forwards operations on it to the object, optionally trapping(intercepting) some of them.

  • It can wrap any kind of object, including classes and functions.

  • Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.

  • As always you can refer here for full context.

  • The syntax is like below

           let proxy = new Proxy(target, { /* traps */});
    
  • The proxy object allows us to create virtual properties and methods, implement default values, observable objects, function decorators and so much more.

  • It can achieve these behaviors via calling internal methods of JavaScript.([[GET]], [[SET]], etc...)

  • For Internal methods, there are corresponding traps in Proxy. We can see from the below table

2.jpg

  • So let's deep dive into code. Explanations will be in the comments

  • Let's say we have an array and we want to return "No Elements Exists" if the index is out of bounds. Also, we want to only add numbers to the array. As you see, we want to intercept array internal methods and make them behave just like we want. Note: Since writing code directly breaks some layouts and does not seem good. So I am sharing the screenshot of the code. I will also share the GitHub address of the code.

1.jpg


Intercepting a method

  • Let's say we have a fetch method used along with the company. At some point, we need to pass a standard header to our API calls. For this case, we need to use a middleware aka interceptor.

  • There is 2 way to implement a middleware:

  • Create a custom wrapper for the fetch method. But this is not the ideal. Because we have to change fetch to fetchWrapper everywhere in the code which seems pretty risky and time-consuming.

  • A better and nicer way is of course using Proxy :). We can use the apply trap to intercept the method execution. Let us see the code :

    3.jpg


Using as a wrapper

  • Imagine we have a function called delay. This function takes a function and a millisecond parameter and executes this function parameter after provided milliseconds. Here we can just return a regular wrapper function instead of a proxy object. But with this, we lose the original function properties like length, name, etc...

    4.jpg


Create private object properties

  • Let's say we assume a property that starts with '_' is `private property of an object.

  • Nobody should access(get), write(set), enumerate(ownKeys) and delete(deleteProperty) it.

  • We can achieve such behavior with Proxy

    5.jpg


Here is another code sample to demonstrate the Proxy API in Javascript.

import { isValidEmail } from './validator.js';

const user = {
  firstName: 'John',
  lastName: 'Doe',
  username: 'johndoe',
  age: 42,
  email: 'john@doe.com',
};

const userProxy = new Proxy(user, {
  set: (target, prop, value) => {
    if (prop === 'username') {
      if (!/^[a-z]{3,}$/gi.test(value)) {
        throw new Error(
          `username should be all string and at least 3 or more characters length. Found: ${value}`
        );
      }
    } else if (prop === 'email') {
      if (!isValidEmail(value)) {
        throw new Error(`Email should be valid. Found: ${value}`);
      }
    } else if (prop === 'age') {
      if (typeof value !== 'number' || value < 18) {
        throw new Error(
          `Age  should be number and at least 18. Found: ${value}`
        );
      }
    }
    return Reflect.set(target, prop, value);
  },
  get: (target, prop) => {
    console.log(
      `${new Date().toUTCString()} | The value of ${prop} is ${target[prop]}`
    );
    return Reflect.get(target, prop);
  },
});

userProxy.username = 'avbc';
userProxy.username;

I will also write an article about Reflect API in the second part. Until then stay tuned, bye-bye.

Source: Awesome site to learn/master javascript

GitHub Code Samples

Did you find this article valuable?

Support Chety by becoming a sponsor. Any amount is appreciated!