🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

proxy-extend

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

proxy-extend

Transparently extend a JS object with additional properties (using ES6 Proxy)

Source
npmnpm
Version
0.1.0
Version published
Weekly downloads
80
40.35%
Maintainers
1
Weekly downloads
 
Created
Source

proxy-extend

npm Travis

Transparently extend any JS object, using ES6 Proxy.

Motivation

Given some existing JS value, you may want to add some information to this value without actually modifying the original. The simplest way to do so is to create a wrapper around the value:

const someValue = getValue();

const someValueAnnotated = {
    value: someValue,
    status: 'ready',
};

One drawback of using a wrapper object, is that the newly annotated value now has a different interface from the original. That means that any consuming code will need to know about the wrapper and "unwrap" it do anything with it.

Using ES6 Proxy, we can make the wrapper have the same interface as the original value, allowing us to pass the wrapped value to any consuming code without the consumer needing to know whether it has been proxied or not.

Usage

import ProxyExtend from 'proxy-extend';

const user = { name: 'John' }; // Some value to be extended

const userExtended = ProxyExtend(user, { status: 'ready' });

// The extended value has the same interface as the original
userExtended.name; // 'John'
({ ...userExtended }); // { name: 'John' }

// But we can also access our annotation, if we know the name of the key
console.log(userExtended.status); // { status: 'ready' }

To make sure that we do not conflict with any existing properties on the original value, it is useful to use a Symbol as the key of the annotation:

import ProxyExtend from 'proxy-extend';

const user = { name: 'John' };

const meta = Symbol('meta'); // Private symbol

const userExtended = ProxyExtend(user, { [meta]: 'some metadata' });
userExtended.name; // 'John'
userExtended[meta]; // 'some metadata'

Limitations

Due to the nature of Proxy, we can only use an object as target value. This library supports any JS object, including plain objects, arrays, functions, and class constructors. We also support a few kinds of primitives by emulating them using objects:

  • null (using an empty object)
  • Strings (using boxed String)
  • Numbers (using boxed Number)

Keywords

proxy

FAQs

Package last updated on 19 Oct 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts