define-accessor2
⭐️ Define feature-rich properties using decorators or plain functions. An extended version of Object.defineProperty ⭐️
Features
- no dependencies
- supports decorators for methods and class properties
- supports legacy and current draft of decorator specification
- lazy properties
- cached properties - cache the value returned by the accessor getter. Cached value can be flushed later
- validation hook
- Joi validation out of the box
- built-in basic type system (see Built-in types)
- automatically flushes getter cache after changing related properties
- defining custom validators
- isolated contexts to define validators in a local scope
- chaining methods - can create chaining methods like getPropName and setPropName
- type predicates (isNumber, isNull etc)
Installation
Install for node.js using npm/yarn:
$ npm install define-property2 --save
$ yarn add define-property2
const defineAccessor= ;
Playground
- Clone
https://github.com/DigitalBrainJS/define-accessor2.git
repo - Run
npm install
to install dev-dependencies - Open
sandbox/sandbox.js
file with a basic example of using library decorators - Run this file using
npm run sandbox
ornpm run sandbox:watch
command to see the result
Usage examples
A basic example of using library decorators (with plugin-proposal-decorators and plugin-proposal-class-properties babel plugins):
const type string number array = ; @string name = ''; @ foo = 123; @array bar = ; const cat = ;catname = 'Lucky'; // Okcatfoo = 123;catfoo = '123';catbar = 1 2 3; catname = 123; // TypeError: Property name accepts String, but number givencatfoo = true; // TypeError: Property foo accepts String|Number, but boolean givencatbar= {}; //Property bar accepts Array, but object given
More complex:
const type cached touches validate accessor defineValidator string= ;const hash = ;const validator= ;const Joi= ; //import all methods as validators predicates; // cached value @cached { console; return ; } // this prop affects 'sha' prop @ @string name= 'anonymous'; @ @ foo= 30; // configure all the necessary accessor features in one decorator (recommended way) @ email= ''; // Joi validator can be used out of the box for complex properties validation @ labels= ; const model= ; console; // 'anonymous'console; // calc shaconsole; // just return the cached valuemodelname= 'admin';console; // calc shamodelemail= 'admin@google.com';console;modelfoo= true;modellabels= '123';
Just using plain functions without any decorators
const defineAccessor TYPE_NUMBER TYPE_STRING= ; const obj= {}; ; //or using type bit mask ;
Validate with Joi:
const defineAccessor= ; const Joi = ; const user= {}; ; userage= 30; //ok, now age= 30 userage= 150; //ValidationError: value (150) is not valid for property (age). Reason: "value" must be less than or equal to 100
Custom validator:
//import library and create a new context for a local validator definition const defineAccessor defineValidator= ; const validator= ; const model= {}; ; ;
const defineAccessor flushAccessor= ;const hash = ; const obj= {}; const normalize = str; const _name=
Functional diagram
API
define-accessor2
- define-accessor2
- module.exports ⏏
- instance
- .defineAccessor(obj, prop, [descriptor]) ⇒
PrivatePropKey
- .defineAccessor(obj, props, [descriptor]) ⇒
Array.<PrivatePropKey>
- .defineAccessor(obj, props, [options]) ⇒
Object.<PrivatePropKey>
- .flushAccessor(obj, ...props) ⇒
boolean
- .privateSymbol(obj, prop) ⇒
Symbol
|null
- .defineValidator(name, fn) ⇒
this
- .defineValidator(validators)
- .newContext() ⇒
Context
- .accessor(accessorDescriptor) ⇒
MethodDecorator
- .accessor([get], [set], [accessorDescriptor]) ⇒
MethodDecorator
- .lazy() ⇒
MethodDecorator
- .cached() ⇒
MethodDecorator
- .chains() ⇒
MethodDecorator
- .type(type) ⇒
MethodDecorator
- .validate(validator) ⇒
MethodDecorator
- .touches(props) ⇒
MethodDecorator
- .undefined() ⇒
MethodDecorator
- .null() ⇒
MethodDecorator
- .boolean() ⇒
MethodDecorator
- .number() ⇒
MethodDecorator
- .string() ⇒
MethodDecorator
- .function() ⇒
MethodDecorator
- .object() ⇒
MethodDecorator
- .symbol() ⇒
MethodDecorator
- .bigint() ⇒
MethodDecorator
- .integer() ⇒
MethodDecorator
- .infinity() ⇒
MethodDecorator
- .nan() ⇒
MethodDecorator
- .date() ⇒
MethodDecorator
- .promise() ⇒
MethodDecorator
- .regexp() ⇒
MethodDecorator
- .error() ⇒
MethodDecorator
- .set() ⇒
MethodDecorator
- .map() ⇒
MethodDecorator
- .defineAccessor(obj, prop, [descriptor]) ⇒
- inner
- ~Context
- ~SetterFunction ⇒
any
- ~GetterFunction ⇒
any
- ~ValidateFunction ⇒
Boolean
- ~PropertyKey :
String
|Symbol
- ~PrivatePropKey :
Symbol
- ~AccessorDescriptor :
Object
- ~ValidatorPredicate ⇒
Boolean
- ~BasicType :
Number
|String
- ~AssertionFunction ⇒
Boolean
- instance
- module.exports ⏏
module.exports ⏏
The default library context. Call context.newContext() to return a new context inherited from the current. This allows you to create an isolated library scope, which does not affect any others in case of defining a custom validator.
PrivatePropKey
module.exports.defineAccessor(obj, prop, [descriptor]) ⇒ Defines a single accessor
Kind: instance method of module.exports
Param | Type | Description |
---|---|---|
obj | Object |
target object |
prop | PropertyKey |
property key |
[descriptor] | AccessorDescriptor |
Example
Array.<PrivatePropKey>
module.exports.defineAccessor(obj, props, [descriptor]) ⇒ Defines several accessors with the same descriptor
Kind: instance method of module.exports
Param | Type | Description |
---|---|---|
obj | Object |
target object |
props | Array.<PropertyKey> |
properties list |
[descriptor] | AccessorDescriptor |
Example
Object.<PrivatePropKey>
module.exports.defineAccessor(obj, props, [options]) ⇒ Defines several accessors using hash map
Kind: instance method of module.exports
Returns: Object.<PrivatePropKey>
- object of private properties that refer to the defined accessors
Param | Type | Description |
---|---|---|
obj | Object |
target object |
props | Object.<PropertyKey> |
properties hash map |
[options] | Object |
|
[options.prefix] | String |
add prefix for each property key of the returned object |
Example
const _name _surname=
boolean
module.exports.flushAccessor(obj, ...props) ⇒ flush accessor's cache
Kind: instance method of module.exports
Returns: boolean
- true if flushed successfully
Param | Type | Description |
---|---|---|
obj | Object |
target object |
...props | PropertyKey |
public accessor's key |
Example
Symbol
| null
module.exports.privateSymbol(obj, prop) ⇒ retrieve the private accessor symbol assigned to the accessor
Kind: instance method of module.exports
Param | Type |
---|---|
obj | Object |
prop | PropertyKey |
this
module.exports.defineValidator(name, fn) ⇒ Defines a new validator in the current library context
Kind: instance method of module.exports
Param | Type | Description |
---|---|---|
name | String |
validator's name |
fn | ValidatorPredicate |
validator predicate function |
Example
const validator = ;;
module.exports.defineValidator(validators)
Defines a new validator in the current library context
Kind: instance method of module.exports
Param | Type |
---|---|
validators | Object |
Example
const validator = ;;
Context
module.exports.newContext() ⇒ creates a new library context
Kind: instance method of module.exports
Example
const defineAccessor flushAccessor defineValidator= //define custom validators for the current and inherited from the current contexts only;
MethodDecorator
module.exports.accessor(accessorDescriptor) ⇒ accessor decorator
Kind: instance method of module.exports
Param |
---|
accessorDescriptor |
MethodDecorator
module.exports.accessor([get], [set], [accessorDescriptor]) ⇒ Kind: instance method of module.exports
Param | Type | Description |
---|---|---|
[get] | function |
getter function, can be omitted |
[set] | function |
setter function, can be omitted |
[accessorDescriptor] | AccessorDescriptor |
accessor descriptor |
MethodDecorator
module.exports.lazy() ⇒ lazy decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.cached() ⇒ cached decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.chains() ⇒ cached decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.type(type) ⇒ type decorator
Kind: instance method of module.exports
Param | Type |
---|---|
type | BasicType |
MethodDecorator
module.exports.validate(validator) ⇒ validate decorator
Kind: instance method of module.exports
Param | Type |
---|---|
validator | BasicType |
MethodDecorator
module.exports.touches(props) ⇒ touches decorator
Kind: instance method of module.exports
Param | Type |
---|---|
props | PropertyKey | Array.<PropertyKey> |
MethodDecorator
module.exports.undefined() ⇒ Undefined decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.null() ⇒ Null decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.boolean() ⇒ Boolean decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.number() ⇒ Number decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.string() ⇒ string decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.function() ⇒ Function decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.object() ⇒ Object decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.symbol() ⇒ Symbol decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.bigint() ⇒ BigInt decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.integer() ⇒ Integer decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.infinity() ⇒ Infinity decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.nan() ⇒ NaN decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.date() ⇒ Date decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.promise() ⇒ Promise decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.regexp() ⇒ RegExp decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.error() ⇒ Error decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.set() ⇒ Set decorator
Kind: instance method of module.exports
MethodDecorator
module.exports.map() ⇒ Map decorator
Kind: instance method of module.exports
module.exports~Context
Library context class
Kind: inner class of module.exports
any
module.exports~SetterFunction ⇒ Kind: inner typedef of module.exports
Returns: any
- value to store in the private property
Param | Type | Description |
---|---|---|
newValue | any |
new value to set |
currentValue | any |
current private value |
propKey | PropertyKey |
public property key |
privateKey | PrivatePropKey |
private property key |
any
module.exports~GetterFunction ⇒ Kind: inner typedef of module.exports
Param | Type | Description |
---|---|---|
currentValue | any |
current private value |
propKey | PropertyKey |
public property key |
Boolean
module.exports~ValidateFunction ⇒ Kind: inner typedef of module.exports
Throws:
- Error
Param | Type | Description |
---|---|---|
value | any |
value to validate |
propKey | PropertyKey |
public property key |
String
| Symbol
module.exports~PropertyKey : Kind: inner typedef of module.exports
Symbol
module.exports~PrivatePropKey : Kind: inner typedef of module.exports
Object
module.exports~AccessorDescriptor : Accessor's descriptor.
Kind: inner typedef of module.exports
Properties
Name | Type | Default | Description |
---|---|---|---|
[get] | GetterFunction |
|
getter function |
[set] | SetterFunction |
|
setter function |
[writable] | Boolean |
false |
if setter is not present indicates whether accessor's value can be set |
[enumerable] | Boolean |
false |
|
[configurable] | Boolean |
false |
|
[cached] | Boolean |
false |
cache getter result until it will be flushed by flushAccessor or other related accessor |
[lazy] | Boolean |
false |
indicates whether the accessor should be a lazy computing property |
[virtual] | Boolean |
false |
if true a private property is not created |
[chains] | Boolean |
false |
create get/set chains for property (like getPropName()/setPropName(value)) |
[touches] | PropertyKey | Array.<PropertyKey> |
|
a key of accessor whose value depends on this |
[type] | BasicType |
|
built-type |
[validate] | ValidateFunction |
|
validator function |
[value] | * |
value to set after initialization |
Boolean
module.exports~ValidatorPredicate ⇒ Kind: inner typedef of module.exports
Param | Type | Description |
---|---|---|
value | any |
value to test |
Number
| String
module.exports~BasicType : Basic type.
Kind: inner typedef of module.exports
Boolean
module.exports~AssertionFunction ⇒ Kind: inner typedef of module.exports
Returns: Boolean
- false if test failed
Param | Type | Description |
---|---|---|
value | Any |
value to test |
Built-in types
The library's type system consist of native JS types and extended pseudotypes. The following types do not overlap, unlike native javascript types. For example, null is not an object, NaN is not a number, and so on.
- Undefined (TYPE_UNDEFINED)
- Null (TYPE_NULL)
- Boolean (TYPE_BOOLEAN)
- Number (TYPE_NUMBER)
- String (TYPE_STRING)
- Function (TYPE_FUNCTION)
- Object (TYPE_OBJECT)
- Symbol (TYPE_SYMBOL)
- BigInt (TYPE_BIGINT)
- Array (TYPE_ARRAY)
- Infinity (TYPE_INFINITY)
- NaN (TYPE_NAN)
- Date (TYPE_DATE)
- Promise (TYPE_PROMISE)
- RegExp (TYPE_REGEXP)
- Error (TYPE_ERROR)
- Set (TYPE_SET)
- Map (TYPE_MAP)
An exception is the integer pseudotype which is an integer and a number types.
- Integer (TYPE_INTEGER)
Special type:
- Any (TYPE_ANY)
There are predicates for each type named like isUndefined(value), isNumber(value) etc.
You can combine these types:
- type: 'string|number' // strings
- type: TYPE_STRING|TYPE_NUMBER //bit mask
- type: string|number // decorators are implicitly converted to a type bit mask using the valueOf() internal method
Decorators
The library supports both versions of the decorators specification (legacy & current draft). There are following decorators:
- lazy
- cached
- touches
- type
- validate
- accessor
- and decorators for each basic type (string, number, array etc. see Built-in types)
Each decorator has valueOf method that returns a type bit mask, so it's possible to pass decorators as a type:
@type(number|string)
Contribution
Feel free to fork, open issues, enhance or create pull requests.
License
The MIT License Copyright (c) 2019 Dmitriy Mozgovoy robotshara@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.