define-accessor2
v1.0.1
Published
Define feature-rich properties using decorators or plain functions. An extended version of Object.defineProperty
Downloads
20
Maintainers
Readme
define-accessor2
:star: Define feature-rich properties using decorators or plain functions. An extended version of Object.defineProperty :star:
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}= require('define-accessor2');
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} = require("define-accessor2");
class Cat {
@string
name = '';
@type(string | number)
foo = 123;
@array
bar = [];
}
const cat = new Cat();
cat.name = 'Lucky'; // Ok
cat.foo = 123;
cat.foo = '123';
cat.bar = [1, 2, 3];
cat.name = 123; // TypeError: Property name accepts String, but number given
cat.foo = true; // TypeError: Property foo accepts String|Number, but boolean given
cat.bar= {}; //Property bar accepts Array, but object given
More complex:
const {type, cached, touches, validate, accessor, defineValidator, string}= require('define-accessor2');
const hash = require('object-hash');
const validator= require('validator');
const Joi= require('@hapi/joi');
//import all methods as validators predicates
defineValidator(validator);
class Model{
// cached value
@cached
get sha(){
console.log('calc sha');
return hash(this);
}
// this prop affects 'sha' prop
@touches('sha')
@string
name= 'anonymous';
@touches('sha')
@type('number|string')
foo= 30;
// configure all the necessary accessor features in one decorator (recommended way)
@accessor({
touches: 'sha',
validate: 'isEmail'
})
email= '';
// Joi validator can be used out of the box for complex properties validation
@validate(Joi.array().items(Joi.string()))
labels= [];
}
const model= new Model();
console.log(model.name); // 'anonymous'
console.log(model.sha); // calc sha
console.log(model.sha); // just return the cached value
model.name= 'admin';
console.log(model.sha); // calc sha
model.email= '[email protected]';
console.log(model.sha);
model.foo= true;
model.labels= ['123'];
Just using plain functions without any decorators
const {defineAccessor, TYPE_NUMBER, TYPE_STRING}= require('define-accessor2');
const obj= {};
defineAccessor(obj, 'someProp', {
type: 'string|number'
});
//or using type bit mask
defineAccessor(obj, 'someProp', {
type: TYPE_STRING|TYPE_NUMBER
});
Validate with Joi:
const {defineAccessor}= require('define-accessor2');
const Joi = require('@hapi/joi');
const user= {};
defineAccessor(user, 'age', {
validate: Joi.number().integer().min(0).max(100),
set(newValue, prevValue){
//do some work
return newValue; //set newValue to the property age
}
});
user.age= 30; //ok, now age= 30
user.age= 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}= require('define-accessor2').newContext();
const validator= require('validator');
const model= {};
defineValidator({
mongoId: validator.isMongoId
});
defineAccessor(model, 'id', {
validate: 'mongoId'
});
const {defineAccessor, flushAccessor}= require('define-accessor2');
const hash = require('object-hash');
const obj= {};
const normalize = (str)=> str.replace(/^\w/, (str)=> str.toUpperCase());
const {_name}= defineAccessor(obj, {
hash: {
get(){
return hash(this);
},
cached: true
},
name: {
validate(value, {reject, set}){
typeof value!=='string' && reject('must be a string');
value= value.trim();
!/^[a-zA-Z]+$/.test(value) && reject('only a-zA-Z allowed');
// alternative way to reject
if( value.length<= 3) return 'length should be greater than 3';
// returning other values than 'true' and 'undefined' treated, as rejection,
// strings are considered as rejection reason
set(value); // change the value
},
set: normalize,
touches: ['hash'],
value: 'Jon'
},
email: {
validate: validator.isEmail
}
}, {prefix: '_'})
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
- 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.
Kind: Exported member
module.exports.defineAccessor(obj, prop, [descriptor]) ⇒ PrivatePropKey
Defines a single accessor
Kind: instance method of module.exports
| Param | Type | Description | | --- | --- | --- | | obj | Object | target object | | prop | PropertyKey | property key | | [descriptor] | AccessorDescriptor | |
Example
defineAccessor(obj, "age", {
get(){
return 99;
}
})
module.exports.defineAccessor(obj, props, [descriptor]) ⇒ Array.<PrivatePropKey>
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
defineAccessor(obj, ["name", "surname"], {
get(privateValue, propKey){
switch(propKey){
case 'name':
return 'John';
case 'surname':
return 'Connor';
}
}
})
module.exports.defineAccessor(obj, props, [options]) ⇒ Object.<PrivatePropKey>
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}= defineAccessor(obj, {
name: {
get(){
return 'John';
}
},
surname: {
get(){
return 'Connor';
}
}
}, {
prefix: '_'
})
module.exports.flushAccessor(obj, ...props) ⇒ boolean
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
defineAccessor(obj, "hash", {
get(){
return calcObjectSHA(this);
}
})
flushAccessor(obj, 'hash')
module.exports.privateSymbol(obj, prop) ⇒ Symbol | null
retrieve the private accessor symbol assigned to the accessor
Kind: instance method of module.exports
| Param | Type | | --- | --- | | obj | Object | | prop | PropertyKey |
module.exports.defineValidator(name, fn) ⇒ this
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 = require('validator');
defineValidator('email', validator.isEmail);
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 = require('validator');
defineValidator({
email: validator.isEmail,
ip: validator.isIP
});
module.exports.newContext() ⇒ Context
creates a new library context
Kind: instance method of module.exports
Example
const {defineAccessor, flushAccessor, defineValidator}= require('define-accessor2').newContext()
//define custom validators for the current and inherited from the current contexts only
defineValidator({
even: (value)=> typeof value && value % 2===0,
odd: (value)=> typeof value && Math.abs(value % 2)===1,
});
module.exports.accessor(accessorDescriptor) ⇒ MethodDecorator
accessor decorator
Kind: instance method of module.exports
| Param | | --- | | accessorDescriptor |
module.exports.accessor([get], [set], [accessorDescriptor]) ⇒ MethodDecorator
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 |
module.exports.lazy() ⇒ MethodDecorator
lazy decorator
Kind: instance method of module.exports
module.exports.cached() ⇒ MethodDecorator
cached decorator
Kind: instance method of module.exports
module.exports.chains() ⇒ MethodDecorator
cached decorator
Kind: instance method of module.exports
module.exports.type(type) ⇒ MethodDecorator
type decorator
Kind: instance method of module.exports
| Param | Type | | --- | --- | | type | BasicType |
module.exports.validate(validator) ⇒ MethodDecorator
validate decorator
Kind: instance method of module.exports
| Param | Type | | --- | --- | | validator | BasicType |
module.exports.touches(props) ⇒ MethodDecorator
touches decorator
Kind: instance method of module.exports
| Param | Type | | --- | --- | | props | PropertyKey | Array.<PropertyKey> |
module.exports.undefined() ⇒ MethodDecorator
Undefined decorator
Kind: instance method of module.exports
module.exports.null() ⇒ MethodDecorator
Null decorator
Kind: instance method of module.exports
module.exports.boolean() ⇒ MethodDecorator
Boolean decorator
Kind: instance method of module.exports
module.exports.number() ⇒ MethodDecorator
Number decorator
Kind: instance method of module.exports
module.exports.string() ⇒ MethodDecorator
string decorator
Kind: instance method of module.exports
module.exports.function() ⇒ MethodDecorator
Function decorator
Kind: instance method of module.exports
module.exports.object() ⇒ MethodDecorator
Object decorator
Kind: instance method of module.exports
module.exports.symbol() ⇒ MethodDecorator
Symbol decorator
Kind: instance method of module.exports
module.exports.bigint() ⇒ MethodDecorator
BigInt decorator
Kind: instance method of module.exports
module.exports.integer() ⇒ MethodDecorator
Integer decorator
Kind: instance method of module.exports
module.exports.infinity() ⇒ MethodDecorator
Infinity decorator
Kind: instance method of module.exports
module.exports.nan() ⇒ MethodDecorator
NaN decorator
Kind: instance method of module.exports
module.exports.date() ⇒ MethodDecorator
Date decorator
Kind: instance method of module.exports
module.exports.promise() ⇒ MethodDecorator
Promise decorator
Kind: instance method of module.exports
module.exports.regexp() ⇒ MethodDecorator
RegExp decorator
Kind: instance method of module.exports
module.exports.error() ⇒ MethodDecorator
Error decorator
Kind: instance method of module.exports
module.exports.set() ⇒ MethodDecorator
Set decorator
Kind: instance method of module.exports
module.exports.map() ⇒ MethodDecorator
Map decorator
Kind: instance method of module.exports
module.exports~Context
Library context class
Kind: inner class of module.exports
module.exports~SetterFunction ⇒ any
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 |
module.exports~GetterFunction ⇒ any
Kind: inner typedef of module.exports
| Param | Type | Description | | --- | --- | --- | | currentValue | any | current private value | | propKey | PropertyKey | public property key |
module.exports~ValidateFunction ⇒ Boolean
Kind: inner typedef of module.exports
Throws:
- Error
| Param | Type | Description | | --- | --- | --- | | value | any | value to validate | | propKey | PropertyKey | public property key |
module.exports~PropertyKey : String | Symbol
Kind: inner typedef of module.exports
module.exports~PrivatePropKey : Symbol
Kind: inner typedef of module.exports
module.exports~AccessorDescriptor : Object
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 |
module.exports~ValidatorPredicate ⇒ Boolean
Kind: inner typedef of module.exports
| Param | Type | Description | | --- | --- | --- | | value | any | value to test |
module.exports~BasicType : Number | String
Basic type.
Kind: inner typedef of module.exports
module.exports~AssertionFunction ⇒ Boolean
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 [email protected]
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.