SN Blog

What are ES6 Proxies and how to use them?

☕ 3 min read 377

What are ES6 Proxies and how to use them?

First we should understand what proxies are actually. Using JavaScript proxies you can wrap an existing object and intercept access to its attributes or methods, even if they don't exist. You can also redefine fundamental operations for that object.

Syntax

There are 2 main terms in using Proxy.

Target - is the original object you want to wrap. It can be everything, also function.

Handler - is an object which define methods that intercept operations. These methods are also called "traps".

Basic Example

Here is the simplest example of Proxy. We have a dictionary with english and bulgarian translation of a few words. So what we want to do is get the bulgarian translation. We can see that everything is working as normal and when we want a word that is not included in the dictionary we get undefined.

Proxy Basic Example

What about instead of this we want to return an appropriate message. More, we can add validations on setters. Here is an example:

Proxy Dictionary Example

Dynamic API Example

We saw a basic example of using Proxy and how to redefine operations. But let's see something a bit more interesting. Let's create an API that can intercept method calls that don't exist. For example we want to call an API with method that can include value or body represented as query and the proxy should return dynamically implement its functionality in runtime.

Proxy Dynamic API Example

Let me explain what the code is doing. First we are getting the type of the method which can be GET, POST, PATCH, DELETE. Then we want to get the endpoint of the method. After that we check if the method is GET and have query parameters, we add them to the endpoint if not, we check if there is body of the request. Finally we display the API call result.

To summarise a proxy can be used wherever an object is expected, and the complex functionality that proxies provide with just a few lines of code makes it an ideal feature for metaprogramming.

📩 Subscribe for my newsletter in order to read other interesting topics like that!

0 Comments

Add a comment