Techumber

Javascript ES6 Proxy

Github avatar
December 02, 2021.2 min read

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.

client
Proxy
ServerA
ServerB
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

Internal Method Method Triggers when…
[[Get]] get reading a property
[[Set]] set writing to a property
[[HasProperty]] has in operator
[[Delete]] deleteProperty delete operator
[[Call]] apply function call
[[Construct]] construct new operator
[[GetPrototypeOf]] getPrototypeOf Object.getPrototypeOf
[[SetPrototypeOf]] setPrototypeOf Object.setPrototypeOf
[[IsExtensible]] isExtensible Object.isExtensible
[[PreventExtensions]] preventExtensions Object.preventExtensions
[[DefineOwnProperty]] defineProperty Object.defineProperty, Object.defineProperties
[[GetOwnProperty]] getOwnPropertyDescriptor Object.getOwnPropertyDescriptor, for..in, Object.keys/values/entries
[[OwnPropertyKeys]] ownKeys Object.getOwnPropertyNames, Object.getOwnPropertySymbols, for..in, Object.keys/values/entries

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


...