Techumber
Home Blog Work

Javascript ES6 Proxy

Published on December 2, 2021

In Server side proxy are a interface instead of calling the service directly we would have proxy server where It would forward the request to main service.

We could abstract all the details of the main service or switch between different service int the background.

graph TD;
    client-->Proxy;
    Proxy-->ServerA;
    Proxy-->ServerB;
    Proxy-->ServerC;

ES6 Proxy

We could the same with for Javascript Object. We can create a proxy for javascript Object where we can provider a interface for Object to hide internal details of the objects.

Syntax:

const proxy = new Proxy(target, config)

target is what object we want to hide. config is the proxy configuration.

Now, Let’s see how we can configure any object.

Example

set

const engToSpanish = new Map();
engToSpanish.set('hi', 'Hola');

proxy = new Proxy(engToSpanish, {
	get(target, prop) {
		if(target.has(prop)) {
			return target.get(prop);
		} else {
			return 'Oops! Word not found'
		}
	}
})

console.log(proxy.hi) // Hola
console.log(proxy.car) // 'Oops! Word not found'

##Set

Same way we can also use set function to manipulate target Object.

let numberOnlyArray = [];

proxy = new Proxy(numberOnlyArray, {
	set(target, prop, val) {
		if (typeof val === 'number') {
			target[prop] = val 
			return true;
		} else {
			throw new Error('Oops! Numbers only');
			return false;
		}
	}
})
proxy.push(1) // 1
proxy.push('hi') // Oops! Numbers only

Don’t forget return true for success.

Other config methods

InternalMethodMethod Triggers when…
[[Get]]getreading a property
[[Set]]setwriting to a property
[[HasProperty]]hasin operator
[[Delete]]deletePropertydelete operator
[[Call]]applyfunction call
[[Construct]]constructnew operator
[[GetPrototypeOf]]getPrototypeOfObject.getPrototypeOf
[[SetPrototypeOf]]setPrototypeOfObject.setPrototypeOf
[[IsExtensible]]isExtensibleObject.isExtensible
[[PreventExtensions]]preventExtensionsObject.preventExtensions
[[DefineOwnProperty]]definePropertyObject.defineProperty, Object.defineProperties
[[GetOwnProperty]]getOwnPropertyDescriptorObject.getOwnPropertyDescriptor, for..in, Object.keys/values/entries
[[OwnPropertyKeys]]ownKeysObject.getOwnPropertyNames, Object.getOwnPropertySymbols, for..in, Object.keys/values/entries

Read More https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy