@haixing_hu/common-decorator is a JavaScript library of common decorators, provides decorators to add common methods to domain classes. The library supports the most recent (currently May 2023) stage 3 proposal of JavaScript decorators.
-
Usage
-
@Model Decorator
- Instance method: Class.prototype.assign(obj, options = undefined)
- Instance method: Class.prototype.clone()
- Instance method: Class.prototype.isEmpty()
- Instance method: Class.prototype.clear()
- Instance method: Class.prototype.equals(other)
- Instance method: Class.prototype.generateId()
- Instance method: Class.prototype.normalizeField(field)
- Instance method: Class.prototype.normalize(fields)
- Instance method: Class.prototype.validateField(field)
- Instance method: Class.prototype.validate(fields)
- Instance method: Class.prototype.toJSON(key, options = undefined)
- Instance method: Class.prototype.toJsonString(options = undeinfed)
- Class method: Class.create(obj, options = undefined)
- Class method: Class.createArray(array, options = undefined)
- Class method: Class.createPage(page, options = undefined)
- Class method: Class.isNullishOrEmpty()
- Class method: Class.parseJsonString(json, options=undefined)
- Usage Examples
-
@Enum Decorator
- Enumerator Fields
- Instance method: Class.prototype.toString()
- Instance method: Class.prototype.toJSON()
- Class method: Class.values()
- Class method: Class.ofValue(value)
- Class method: Class.hasValue(value)
- Class method: Class.ofName(name)
- Class method: Class.hasName(name)
- Class method: Class.ofCode(code)
- Class method: Class.hasCode(code)
- Class method: Class.of(expr)
- Class method: Class.has(expr)
- Usage Example
- DefaultOptions Class
-
@Model Decorator
- Configuration
- Contributing
- License
This decorator is used to decorate a domain model class, which adds the following instance and class methods to the decorated class.
NOTE: If the decorated class already implements any of the following methods, this decorator will not override the methods already implemented by the decorated class.
- Parameters:
-
obj: object
: the object whose fields will be copied to this object, which may have a different prototype to this object. -
options: null|undefined|object
: the additional options for the assignment. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('assign')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object after the assignment. The default value istrue
. -
convertNaming: boolean
, indicates whether to convert the naming style of the target object. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the first argument of theassign()
method. The default value of this argument is'LOWER_UNDERSCORE'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the object calling theassign()
method. The default value of this argument is'LOWER_CAMEL'
. -
types: object
, the additional information about types of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the fields, represented as the constructor function of the type. The default value is{}
. -
elementTypes: object
, the additional information about types of elements of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the elements, represented as the constructor function of the type. The default value is{}
.
-
-
- Returns:
-
object
: the calling object itself.
-
This function copies the fields of the object obj
to this object, only copying
fields defined in this object's class. If a field in the obj
object is
undefined
or null
, it sets the field's value to the default value. Note that
obj
can have a different prototype to this object.
- Parameters: none.
- Returns:
-
object
: a instance of the specified class deep cloned from the calling object.
-
This function deep clones the calling object, returning a new instance of the specified class with the same property values as the calling object. Note that the returned object has the same prototype as the calling object.
- Parameters: none.
- Returns:
-
object
: the calling object itself.
-
This function sets all the properties of this object to their default values. The default value of a field is the value of the field of the default constructed instance of the class.
- Parameters: none.
- Returns:
-
boolean
: whether this object is empty.
-
This function checks if this object is empty, meaning that all of its fields have default values. The default value of a field is the value of the field of the default constructed instance of the class.
- Parameters:
-
other: object
: the object to be compared with this object.
-
- Returns:
-
boolean
: whether this object is deeply equal toother
.
-
This function checks whether this object is deeply equal to other
. Two objects
are deeply equal if and only if they have the same prototype, and all of their
fields are deeply equal. Two fields are deeply equal if and only if they have
the same value, or they are both undefined
or null
. If a field is an array,
it is deeply equal to another array if and only if they have the same length,
and all of their elements are deeply equal. If a field is an object, it is
deeply equal to another object if and only if they have the same prototype,
and all of their fields are deeply equal.
- Parameters: none.
- Returns:
-
string
: the string representation of the generated globally unique ID set to the calling object.
-
If the decorated class defines a property named id
, this instance method
generateId()
is automatically added to the decorated class. Each call to this
method generates a globally unique ID for the current calling object
(represented as a string of an integer), sets the id
field of the calling
object to the generated ID, and returns the generated ID. Note that if a parent
class A
defines the id
field, and a subclass B
inherits the id
field but
does not define its own id
field, the generateId()
method is added only to
class A
, not to class B
.
- Parameters:
-
field: string
: the name of the specified field to be normalized.
-
- Returns:
-
boolean
: whether the specified field was normalized.
-
This function normalizes the specified field of this object. If the object has
the specified field and the specified field is normalizable, the function
normalizes the specified field and returns true
; otherwise, the function does
nothing and returns false
. Note that a field is normalizable if and only if it
is decorated by the @Normalizable
decorator.
- Parameters:
-
fields: undefined | null | string | string[]
: the fields to be normalized. It can be one of the following values:-
undefined
: normalizes all the normalizable fields of this object. -
null
: normalizes all the normalizable fields of this object. -
"*"
: normalizes all the normalizable fields of this object. -
string[]
: normalizes all the normalizable fields whose names are specified in this array.
-
-
- Returns:
-
object
: the normalized calling object.
-
This function normalizes the specified fields of this object. The fields
parameter specifies the names of fields to be normalized. If fields
is
undefined
, null
, or the string "*"
, it normalizes all the normalizable
fields of this object. If fields
is an array of strings, it normalizes all the
normalizable fields whose names are specified in the array. Note that a field is
normalizable if and only if it is decorated by the @Normalizable
decorator.
- Parameters:
-
field: string
: the name of the specified field to be validated.
-
- Returns:
-
ValidationResult | null
: the validation result.
-
This function validates the specified field of this object. If the object has
the specified field and the specified field is validatable, the function
validates the specified field and returns the validation result; otherwise, the
function does nothing and returns null
. Note that a field is validatable if
and only if it is decorated by the @Validatable
decorator.
- Parameters:
-
fields: undefined | null | string | string[]
: the fields to be validated. It can be one of the following values:-
undefined
: validates all the validatable fields of this object. -
null
: validates all the validatable fields of this object. -
"*"
: validates all the validatable fields of this object. -
string[]
: validates all the validatable fields whose names are specified in this array.
-
-
- Returns:
-
ValidationResult
: the validation result.
-
This function validates the specified fields of this object. The fields
parameter specifies the names of fields to be validated. If fields
is
undefined
, null
, or the string "*"
, it validates all the validatable
fields of this object. If fields
is an array of strings, it validates all the
validatable fields whose names are specified in the array. Note that a field is
validatable if and only if it is decorated by the @Validatable
decorator.
- Parameters:
-
key: string
:JSON.stringify()
callstoJSON()
with one parameter, thekey
,which takes the following values:- if this object is a property value, this argument is the property name;
- if this object is in an array, this argument is the index in the array, as a string;
- if
JSON.stringify()
was directly called on this object, this argument is an empty string.
-
options: null|undefined|object
: the additional options for the serialization. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('toJSON')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object before serializing. The default value istrue
. -
removeEmptyFields: boolean
, indicates whether to ignore the empty fields of the object. If it istrue
, the empty fields of the object will be removed before serialization. The default value isfalse
. -
convertNaming: boolean
, indicates whether to convert the naming of properties of the object represented by the result JSON string. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the object calling thetoJSON()
method. The default value of this argument is'LOWER_CAMEL'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the object represented by the result JSON string of thetoJSON()
method. The default value of this argument is'LOWER_UNDERSCORE'
. -
space: string | number
, a string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than 10 is treated as if it were 10). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If this is anything other than a string or number (can be either a primitive or a wrapper object) — for example, isnull
or not provided — no white space is used. The default value of this option isnull
.
-
-
- Returns:
-
object
: the object to be serialized byJSON.stringify()
, which may be a modify copy of this object.
-
This function gets the object to be serialized by JSON.stringify()
.
If the value has a toJSON()
method, it's responsible to define what
data will be serialized. Instead of the object being serialized, the value
returned by the toJSON()
method when called will be serialized.
NOTE: this function returns an object to be serialized by
JSON.stringify()
, instead of a JSON string. Use JSON.stringify()
or this.toJsonString()
methods to serialize this object into a JSON
string.
- Parameters:
-
options: null|undefined|object
: the additional options for the serialization. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('toJSON')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object before serializing. The default value istrue
. -
removeEmptyFields: boolean
, indicates whether to ignore the empty fields of the object. If it istrue
, the empty fields of the object will be removed before serialization. The default value isfalse
. -
convertNaming: boolean
, indicates whether to convert the naming of properties of the object represented by the result JSON string. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the object calling thetoJSON()
method. The default value of this argument is'LOWER_CAMEL'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the object represented by the result JSON string of thetoJSON()
method. The default value of this argument is'LOWER_UNDERSCORE'
. -
space: string | number
, a string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than 10 is treated as if it were 10). Values less than 1 indicate that no space should be used. If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array. If this is anything other than a string or number (can be either a primitive or a wrapper object) — for example, isnull
or not provided — no white space is used. The default value of this option isnull
.
-
-
- Returns:
-
string
: the JSON string serialized from this object, asJSON.stringify()
does, except that this function provides additional stringification options.
-
This function serializes this object into a JSON string.
NOTE: This method supports native bigint
value. For example, the
bigint
value 9223372036854775807n
will be stringify as
9223372036854775807
.
- Parameters:
-
obj: object
: the data object used to create the new instance. -
options: null|undefined|object
: the additional options for the creation. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('assign')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object after the assignment. The default value istrue
. -
convertNaming: boolean
, indicates whether to convert the naming style of the target object. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the first argument of thecreate()
method. The default value of this argument is'LOWER_UNDERSCORE'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the object returned by thecreate()
method. The default value of this argument is'LOWER_CAMEL'
. -
types: object
, the additional information about types of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the fields, represented as the constructor function of the type. The default value is{}
. -
elementTypes: object
, the additional information about types of elements of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the elements, represented as the constructor function of the type. The default value is{}
.
-
-
- Returns:
-
object | null
: if theobj
isundefined
ornull
, returnsnull
; otherwise, returns a new instance of the model class whose fields are initialized with the data in theobj
.
-
This function creates a instance of the specified class from a data object,
whose fields are recursively initialized with properties in the obj
. Note that
obj
can have a different prototype to the specified class.
- Parameters:
-
array: object[]
: the data object array used to create the new array. -
options: null|undefined|object
: the additional options for the creation. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('assign')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object after the assignment. The default value istrue
. -
convertNaming: boolean
, indicates whether to convert the naming style of the target object. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the elements in the first argument of thecreateArray()
method. The default value of this argument is'LOWER_UNDERSCORE'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the elements in the array returned by thecreateArray()
method. The default value of this argument is'LOWER_CAMEL'
. -
types: object
, the additional information about types of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the fields, represented as the constructor function of the type. The default value is{}
. -
elementTypes: object
, the additional information about types of elements of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the elements, represented as the constructor function of the type. The default value is{}
.
-
-
- Returns:
-
object[] | null
: if thearray
isundefined
ornull
, returnsnull
; otherwise, returns a new array of instances of the model class whose fields are initialized with corresponding data object in thearray
.
-
This function creates an array of instances of the specified class from a data
object array. The fields of instances in the returned array are recursively
initialized with corresponding properties of the corresponding data object in
the array
. Note that data objects in array
can have different prototypes to
the specified class.
- Parameters:
-
page: object
: the pagination data object used to create the newPage
instance. -
options: null|undefined|object
: the additional options for the creation. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('assign')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object after the assignment. The default value istrue
. -
convertNaming: boolean
, indicates whether to convert the naming style of the target object. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the elements in thecontent
array of the first argument of thecreatePage()
method. The default value of this argument is'LOWER_UNDERSCORE'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the elements in thecontent
array of thePage
object returned by thecreatePage()
method. The default value of this argument is'LOWER_CAMEL'
. -
types: object
, the additional information about types of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the fields, represented as the constructor function of the type. The default value is{}
. -
elementTypes: object
, the additional information about types of elements of fields of classes. The keys of this object are the path of the fields or sub-fields of the target object, the values are the type of the elements, represented as the constructor function of the type. The default value is{}
.
-
-
- Returns:
-
Page | null
: if thepage
isundefined
ornull
, returnsnull
; otherwise, returns a new instance of thePage
class whose content are initialized with the content of the pagination data objectpage
.
-
This function creates a Page
object, whose content are initialized with the
content of the specified pagination data object. Typically, page
is a list of
domain objects obtained from a server using the GET
method, and the object
should conform to the Page
class definition. This class method returns
a new Page
object, with the content
property being the result of
createArray(page.content, options)
, and the other properties matching those of
the page
object. If page
is not a valid Page
object, it returns null
.
- Parameters:
-
obj: object
: the object to be checked.
-
- Returns:
-
boolean
: whether the specified object isundefined
,null
, or an empty object constructed with default values.
-
This function checks whether the specified object is undefined
, null
, or an
empty object constructed with default values. An object is empty if and only if
all of its fields have default values. The default value of a field is the value
of the field of the default constructed instance of the class. This function is
a convenient method to call Class.prototype.isEmpty()
, with the handling of
nullish values.
- Parameters:
-
json: string
: the JSON string to be parsed. -
options: null|undefined|object
: the additional options for the parsing. If this argument isundefined
ornull
, the default options will be used. The default options can be retrieved by callingDefaultOptions.get('assign')
. Available options are:-
normalize: boolean
, indicates whether to normalize this object after the assignment. The default value istrue
. -
convertNaming: boolean
, indicates whether to convert the naming style of properties of the object represented by the JSON string. The default value isfalse
. -
sourceNamingStyle: string
, the naming style of the source object, i.e., the object represented by the JSON string. The default value of this argument is'LOWER_UNDERSCORE'
. -
targetNamingStyle: string
, the naming style of the target object, i.e., the object returned by theparseJsonString()
method. The default value of this argument is'LOWER_CAMEL'
.
-
-
- Returns:
-
boolean
: whether the specified object isundefined
,null
, or an empty object constructed with default values.
-
This function parses an object of this class from a JSON string.
NOTE: This method supports integer values fall out of IEEE 754 integer
precision. For example, the integer value 9223372036854775807
will be
parsed as the native bigint
value 9223372036854775807n
.
The following is the usage example of the @Model
decorator.
@Model
class Credential {
@Normalizable
@Validator(validateCredentialTypeField)
@Type(CredentialType)
@Label('证件类型')
type = 'IDENTITY_CARD';
@Normalizable(trimUppercaseString)
@Validator(validateCredentialNumberField)
@Label('证件号码')
number = '';
constructor(type = CredentialType.DEFAULT.value, number = '') {
this.type = type;
this.number = number;
}
isIdentityCard() {
return (this.type === 'IDENTITY_CARD');
}
}
@Model
class Person {
@Normalizable(trimString)
@Label('ID')
id = null;
@Normalizable(trimUppercaseString)
@Validator(validatePersonNameField)
@Label('姓名')
name = '';
@Normalizable
@DefaultValidator
@Type(Credential)
@Label('证件')
credential = null;
@Normalizable
@Validator(validatePersonGenderField)
@Type(Gender)
@Label('性别')
gender = '';
@Normalizable(trimString)
@Validator(validatePersonBirthdayField)
@Label('出生日期')
birthday = '';
@Normalizable(trimUppercaseString)
@Validator(validateMobileField)
@Label('手机号码')
mobile = '';
@Normalizable(trimString)
@Validator(validateEmailField)
@Label('电子邮件地址')
@Nullable
email = '';
equals(other) {
if (!(other instanceof PersonWithEquals)) {
return false;
}
if ((this.credential === null) || (other.credential === null)) {
// If one of the two people does not have ID inofmation, it is impossible
// to compare whether they are the same person thus they will be considered
// different.
return false;
}
// Two persons are logically equals if and only if they have the same
// credential.
return (this.credential.type === other.credential.type)
&& (this.credential.number === other.credential.number);
}
}
After applying the @Model
decorator, the following methods will be automatically
added:
Credential.prototype.assign(obj, options = undefined)
Credential.prototype.clear()
Credential.prototype.clone()
Credential.prototype.isEmpty()
Credential.prototype.equals(obj)
Credential.prototype.normalize(fields)
Credential.prototype.validate(fields, options)
Credential.prototype.toJSON(key, options = undefined)
Credential.prototype.toJsonString(options = undefined)
Credential.create(obj, options = undefined)
Credential.createArray(array, options = undefined)
Credential.createPage(page, options = undefined)
Credential.isNullishOrEmpty(obj)
Credential.parseJsonString(json, options = undefined)
Person.prototype.assign(obj, normalized)
Person.prototype.clear()
Person.prototype.clone()
Person.prototype.isEmpty()
Person.prototype.normalize(fields)
Person.prototype.validate(fields, options)
Person.prototype.generateId()
Person.prototype.toJSON(key, options = undefined)
Person.prototype.toJsonString(options = undefined)
Person.create(obj, options = undefined)
Person.createArray(array, options = undefined)
Person.createPage(page, options = undefined)
Person.isNullishOrEmpty(obj)
Person.parseJsonString(json, options = undefined)
NOTE:
- Because the
Credential
class does not have anid
attribute, the@Model
decorator does not add agenerateId()
instance method to it. - Because
Person
already implements thePerson.prototype.equals()
method, the@Model
decorator will not override its own implementation of thePerson.prototype.equals()
method.
This decorator is used to decorate an enumeration class.
An enumeration class is a class whose instances are enumerators. An enumerator is an object with the following properties:
-
value
:the value of the enumerator, which is exactly the name of the static field of the enumeration class that corresponds to the enumerator. -
name
: the display name of the enumerator, which could be specified by the default string or object value of the static field of the enumeration class that corresponds to the enumerator. It the default value is not specified, the name of the enumerator is the same as its value. -
i18n
: the i18n key of the enumerator, which is an optional property. It could be specified by the default object value of the static field of the enumeration class that corresponds to the enumerator. If this property is specified, thename
property will be transformed to agetter
, which will get the i18n value of the enumerator from the i18n resource bundle. -
code
: the code of the enumerator, which is an optional property. It could be specified by the default object value of the static field of the enumeration class that corresponds to the enumerator. - other properties: other properties of the enumerator could be specified by the default object value of the static field of the enumeration class that corresponds to the enumerator.
- Parameters: none.
- Returns:
-
string
: the string representation of this enumerator, which is thevalue
of this enumerator.
-
This function returns the string representation of this enumerator, which is
the value
of this enumerator.
- Parameters: none.
- Returns:
-
string
: the JSON representation of this enumerator, which is the JSON string representation of thevalue
of this enumerator, i.e., the double quoted string of thevalue
.
-
This function returns the JSON representation of this enumerator.
- Parameters: none.
- Returns:
-
Class[]
: the array of all enumerators of this enumeration class.
-
This function returns the array of all enumerators of this enumeration class.
- Parameters:
-
value: string
: the value of the enumerator to be returned. Note that this argument will be trimmed and uppercased to get the actual value of the enumerator.
-
- Returns:
-
Class
: the enumerator in this enumeration class with the specified value, orundefined
if no such enumerator exists.
-
This function returns the enumerator with the specified value.
- Parameters:
-
value: string
: the value of the enumerator to be tested. Note that this argument will be trimmed and uppercased to get the actual value of the enumerator.
-
- Returns:
-
boolean
: returnstrue
if there is an enumerator in this enumeration class with the specified value, orfalse
otherwise.
-
This function tests whether there is an enumerator with the specified value.
- Parameters:
-
name: string
: the name of the enumerator to be returned.
-
- Returns:
-
Class
: the enumerator in this enumeration class with the specified name, orundefined
if no such enumerator exists.
-
This function returns the enumerator with the specified name.
- Parameters:
-
name: string
: the name of the enumerator to be tested.
-
- Returns:
-
boolean
: returnstrue
if there is an enumerator in this enumeration class with the specified name, orfalse
otherwise.
-
This function tests whether there is an enumerator with the specified name.
- Parameters:
-
code: string
: the code of the enumerator to be returned.
-
- Returns:
-
Class
: the enumerator in this enumeration class with the specified code, orundefined
if no such enumerator exists.
-
This function returns the enumerator with the specified value.
- Parameters:
-
code: string
: the code of the enumerator to be tested.
-
- Returns:
-
boolean
: returnstrue
if there is an enumerator in this enumeration class with the specified code, orfalse
otherwise.
-
This function tests whether there is an enumerator with the specified code.
- Parameters:
-
expr: object | string
: the expression corresponds to the enumerator to be returned. The expression could be one of the following:- an enumerator of this enumeration class;
- or the value of an enumerator of this enumeration class;
- or the name of an enumerator of this enumeration class;
- or the code of an enumerator of this enumeration class.
-
- Returns:
-
Class
: the enumerator in this enumeration class corresponds to the specified expression, orundefined
if no such enumerator exists.
-
This function returns the enumerator with the specified value.
- Parameters:
-
expr: object | string
: the expression corresponds to the enumerator to be returned. The expression could be one of the following:- an enumerator of this enumeration class;
- or the value of an enumerator of this enumeration class;
- or the name of an enumerator of this enumeration class;
- or the code of an enumerator of this enumeration class.
-
- Returns:
-
boolean
: returnstrue
if there is an enumerator in this enumeration class corresponds to the specified expression, orfalse
otherwise.
-
This function tests whether there is an enumerator with the specified code.
@Enum
class Gender {
static MALE = 'Male';
static FEMALE = 'Female';
}
The above code is equivalent to the following code:
class Gender {
static MALE = Object.freeze(new Gender('MALE', 'Male'));
static FEMALE = Object.freeze(new Gender('FEMALE', 'Female'));
static values() {
return [ Gender.MALE, Gender.FEMALE ];
}
static ofValue(value) {
switch (value) {
case 'MALE':
return Gender.MALE;
case 'FEMALE':
return Gender.FEMALE;
default:
return undefined;
}
}
static hasValue(value) {
return Gender.ofValue(value) !== undefined;
}
static ofName(name) {
return Gender.values().find((e) => e.name === name);
}
static hasName(name) {
return Gender.ofName(name) !== undefined;
}
static ofCode(code) {
return Gender.values().find((e) => e.code === code);
}
static hasCode(code) {
return Gender.ofCode(code) !== undefined;
}
static of(expr) {
if (expr instanceof Gender) {
return expr;
} else {
return Gender.ofValue(expr) ?? Gender.ofName(expr) ?? Gender.ofCode(expr);
}
}
static has(expr) {
return Gender.of(expr) !== undefined;
}
constructor(value, name) {
this.value = value;
this.name = name;
}
toString() {
return this.value;
}
toJSON() {
return this.value;
}
}
The static fields of the enumeration class could also be specified as objects, which will be used to initialize the enumerators. For example:
@Enum
class Gender {
static MALE = { name: 'Male', i18n: 'i18n.gender.male', code: '001', data: { value: 0 } };
static FEMALE = { name: 'Female', i18n: 'i18n.gender.female', code: '002', data: { value: 1 } };
}
The above code is equivalent to the following code:
class Gender {
static MALE = Object.freeze(new Gender('MALE', 'Male',
{ i18n: 'i18n.gender.male', code: '001', data: {value: 0 } }));
static FEMALE = Object.freeze(new Gender('FEMALE', 'Female',
{ i18n: 'i18n.gender.female', code: '002', data: {value: 1 } }));
...
constructor(value, name, payload) {
this.value = value;
this.name = name;
Object.assign(this, payload);
}
...
}
Note that the enumerator in the above Gender
class has a code
, i18n
and data
properties. Since it has i18n
property which specifies the i18n
key of the enumerator in the resource bundle, the name
property of the
enumerator will be transformed to a getter
which will get the i18n value
corresponding to the i18n key from the i18n resource bundle.
The enumerators can also be defined without default values, for example:
@Enum
class Gender {
static MALE;
static FEMALE;
}
The above code is equivalent to the following code:
class Gender {
static MALE = Object.freeze(new Gender('MALE'));
static FEMALE = Object.freeze(new Gender('FEMALE'));
...
constructor(value) {
this.value = value;
this.name = value;
}
...
}
That is, the name of the enumerator is exactly its value.
The DefaultOptions
class is used to get or set the default options of different
aspects of this library.
The class accesses an internal Map
object. The key of the map is the name
of aspects, and the value of the map is an object representing the default
options of the aspect.
For example, the default options of the assign()
method of the class
decorated by @Model
is stored in the key assign
. That is,
DefaultOption.get('assign')
returns the object representing the default
options of the assign()
method.
The program can change the default options with DefaultOptions.set('key', options)
method.
Currently, the following aspects are supported:
-
assign
: the default options of theClass.prototype.assign()
,Class.create()
,Class.createArray()
,Class.createPage()
,Class.parseJsonString()
methods of the class decorated by@Model
. -
toJSON
: the default options of theClass.prototype.toJSON()
,Class.prototype.toJsonString()
methods of the class decorated by@Model
.
Gets the default options of the specified aspect.
The function returns the object representing the default options of the aspect,
or undefined
if the aspect does not exist. Note that the returned object is a
deep cloned copy of the object stored in the internal map, so that the
modification of the returned object will not affect the default options
stored in the internal map.
import { DefaultOptions } from '@haixing_hu/common-decorator';
const opt1 = DefaultOptions.get('assign');
expect(opt1.convertNaming).toBe(false);
opt1.convertNaming = true;
const opt2 = DefaultOptions.get('assign');
expect(opt2.convertNaming).toBe(false);
Sets the default options of the specified aspect.
This function will merge the new options into the old default options of the aspect. If the new options have the same property as the old default options stored in the internal map, the value of the new options will override the value of the old default options; otherwise, the new property will be added to the old default options.
import { DefaultOptions } from '@haixing_hu/common-decorator';
const opt1 = DefaultOptions.get('assign');
expect(opt1.convertNaming).toBe(false);
DefaultOptions.set('assign', { convertNaming: true });
const opt2 = DefaultOptions.get('assign');
expect(opt2.convertNaming).toBe(true);
expect(opt1.convertNaming).toBe(false);
Gets the default options of the specified aspect, merging the provided default options into the returned object.
NOTE: This function does NOT change the default options stored in the internal map, instead, it returns a new object representing the merged options.
import { DefaultOptions } from '@haixing_hu/common-decorator';
const opt1 = DefaultOptions.get('assign');
expect(opt1.convertNaming).toBe(false);
const opt2 = DefaultOptions.merge('assign', { convertNaming: true });
expect(opt2.convertNaming).toBe(true);
expect(opt1.convertNaming).toBe(false);
const opt3 = DefaultOptions.merge('assign', null);
expect(opt3.convertNaming).toBe(false);
This library uses the most recent (currently May 2023) stage 3 proposal of JavaScript decorators. Therefore, you must configure Babel with @babel/plugin-transform-class-properties and the @babel/plugin-proposal-decorators plugins.
NOTE: To support the stage 3 proposal of JavaScript decorator metadata,
the version of the Babel plugin @babel/plugin-proposal-decorators must be
at least 7.23.0
.
Bundling with webpack
- Install the required dependencies:
yarn add @haixing_hu/common-decorator yarn add --dev @babel/core @babel/runtime @babel/preset-env yarn add --dev @babel/plugin-proposal-decorators @babel/plugin-transform-class-properties @babel/plugin-transform-runtime
- Configure Babel by using the @babel/plugin-transform-class-properties
and @babel/plugin-proposal-decorators plugins. A possible Babel
configuration file
babelrc.json
is as follows:{ "presets": [ "@babel/preset-env" ], "plugins": [ "@babel/plugin-transform-runtime", ["@babel/plugin-proposal-decorators", { "version": "2023-05" }], "@babel/plugin-transform-class-properties" ] }
Bundling with vite
- Install the required dependencies:
yarn add @haixing_hu/common-decorator yarn add --dev @babel/core @babel/runtime @babel/preset-env yarn add --dev @babel/plugin-proposal-decorators @babel/plugin-transform-class-properties @babel/plugin-transform-runtime
- Configure Babel by using @babel/plugin-transform-class-properties and
@babel/plugin-proposal-decorators plugins. A possible Babel configuration
file
babelrc.json
is as follows:Note: When bundling with vite, make sure to set the{ "presets": [ ["@babel/preset-env", { "modules": false }] ], "plugins": [ "@babel/plugin-transform-runtime", ["@babel/plugin-proposal-decorators", { "version": "2023-05" }], "@babel/plugin-transform-class-properties" ] }
modules
parameter of@babel/preset-env
tofalse
. - Configure vite by modifying the
vite.config.js
file to add support for Babel. A possiblevite.config.js
file is as follows:Note: In the above configuration file, we've implemented a simple vite plugin to transpile the code processed by the vite-plugin-vue plugin using Babel. Although there's a vite-plugin-babel plugin that claims to add Babel support to vite, we found it doesn't correctly handle [vue] Single File Components (SFCs). After closely examining its source code, we determined that to achieve correct transpilation, we need to apply Babel after vite-plugin-vue processes the source code. Therefore, the very simple plugin function above suffices for our needs. As an alternative, you can use our version of vite-plugin-babel, and the following is an example configuration:import { fileURLToPath, URL } from 'node:url'; import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import * as babel from '@babel/core'; // A very simple Vite plugin support babel transpilation const babelPlugin = { name: 'plugin-babel', transform: (src, id) => { if (/\.(jsx?|vue)$/.test(id)) { // the pattern of the file to handle return babel.transform(src, { filename: id, babelrc: true, }); } }, }; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue({ script: { babelParserPlugins: ['decorators'], // must enable decorators support }, }), babelPlugin, // must be after the vue plugin ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, });
import { fileURLToPath, URL } from 'node:url'; import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import babel from '@haixing_hu/vite-plugin-babel'; export default defineConfig({ plugins: [ vue({ script: { babelParserPlugins: ['decorators'], // must enable decorators support }, }), babel(), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, });
If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request to the GitHub repository.
@haixing_hu/common-decorator is distributed under the Apache 2.0 license. See the LICENSE file for more details.