Before going into why, lets understand what is it. If you already know, feel free to skip few paragraphs.
There are 3 key terms we need to understand before we proceed:
- Targets : Object or Function to be proxied.
- Handler : The function that do something on Object or Function that is proxied.
- Traps : These are some functions used to work on targets. Click here to read more about traps.
Below is how we defined it
We use Proxy Class from ES6, the arguments, target is the wrap object and handler will be the function used to do some action on target using traps.
Below is a simple example of its usage
We made 2 objects called target and handler, target is a simple object with a message key and handler is an object that have a get key with a function associated with it. We pass 2 objects in proxy class and in return receive a proxy object by which we can access the message property of target object.
Here is an small example of how use it for validation of object values
We use a empty object as a target object and a handler that take set trap on target object and do the validation. Pretty easy right!
Lets look into how we can use it to make API call wrapper.
We have used axios, and then created an instance with our baseURL, created a handler for proxy that return an object of get, post, put, delete, patch function to be used, and at last made an api object which is a proxy object to an empty object target.
We can then use it as :
This can be extended doing validation, value correction, tracing property accesses, warning about unknown properties, negative Array indices, data binding, accessing a restful web service (method calls), revocable references, monitoring async functions, type checking and much more, Read here more
Side note: The examples used can be optimized.
This is my first article on medium 😃 or should i say a new journey of writing begins. 😄
I am happy to receive any feedback may be positive or negative.