@acodeninja/persist 2.2.1 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/type/Model.js CHANGED
@@ -5,10 +5,32 @@ import {monotonicFactory} from 'ulid';
5
5
 
6
6
  const createID = monotonicFactory();
7
7
 
8
- export default class Model {
8
+ /**
9
+ * @class Model
10
+ */
11
+ class Model {
12
+ /**
13
+ * Represents the model's ID field, defined as a required string.
14
+ *
15
+ * @type {StringType.required.constructor}
16
+ * @static
17
+ */
9
18
  static id = StringType.required;
19
+
20
+ /**
21
+ * Tracks whether the model is required in a schema.
22
+ *
23
+ * @type {boolean}
24
+ * @static
25
+ * @private
26
+ */
10
27
  static _required = false;
11
28
 
29
+ /**
30
+ * Creates a new instance of the model, initializing properties based on the provided data.
31
+ *
32
+ * @param {Object} [data={}] - The initial data to populate the model instance.
33
+ */
12
34
  constructor(data = {}) {
13
35
  this.id = `${this.constructor.name}/${createID()}`;
14
36
 
@@ -26,7 +48,13 @@ export default class Model {
26
48
  }
27
49
  }
28
50
 
29
- toData() {
51
+ /**
52
+ * Serializes the model instance into an object, optionally retaining complex types.
53
+ *
54
+ * @param {boolean} [simple=true] - Determines whether to format the output using only JSON serialisable types.
55
+ * @returns {Object} - A serialized representation of the model.
56
+ */
57
+ toData(simple = true) {
30
58
  const model = {...this};
31
59
 
32
60
  for (const [name, property] of Object.entries(this.constructor)) {
@@ -35,23 +63,70 @@ export default class Model {
35
63
  }
36
64
  }
37
65
 
38
- return JSON.parse(JSON.stringify(model, (key, value) => {
39
- if (key && this.constructor.isModel(value)) {
40
- return {id: value.id};
41
- }
42
- return value;
43
- }));
66
+ return JSON.parse(
67
+ JSON.stringify(model, (key, value) => {
68
+ if (key && this.constructor.isModel(value)) {
69
+ return {id: value.id};
70
+ }
71
+ return value;
72
+ }),
73
+ (key, value) => {
74
+ if (!simple) {
75
+ if (this.constructor[key]) {
76
+ if (this.constructor[key].name.endsWith('DateType')) {
77
+ return new Date(value);
78
+ }
79
+
80
+ if (this.constructor[key].name.endsWith('ArrayOf(Date)Type')) {
81
+ return value.map(d => new Date(d));
82
+ }
83
+ }
84
+ }
85
+
86
+ return value;
87
+ },
88
+ );
44
89
  }
45
90
 
91
+ /**
92
+ * Validates the current model instance against the defined schema.
93
+ *
94
+ * @returns {boolean} - Returns `true` if validation succeeds.
95
+ * @throws {ValidationError} - Throws this error if validation fails.
96
+ */
46
97
  validate() {
47
98
  return SchemaCompiler.compile(this.constructor).validate(this);
48
99
  }
49
100
 
101
+ /**
102
+ * Extracts data from the model based on the indexed properties defined in the class.
103
+ *
104
+ * @returns {Object} - A representation of the model's indexed data.
105
+ */
50
106
  toIndexData() {
51
- const output = { id: this.id };
52
- const index = this.constructor.indexedProperties();
107
+ return this._extractData(this.constructor.indexedProperties());
108
+ }
109
+
110
+ /**
111
+ * Extracts data from the model based on the search properties defined in the class.
112
+ *
113
+ * @returns {Object} - A representation of the model's search data.
114
+ */
115
+ toSearchData() {
116
+ return this._extractData(this.constructor.searchProperties());
117
+ }
53
118
 
54
- for (const key of index) {
119
+ /**
120
+ * Extracts specific data fields from the model based on a set of keys.
121
+ *
122
+ * @param {Array<string>} keys - The keys to extract from the model.
123
+ * @returns {Object} - The extracted data.
124
+ * @private
125
+ */
126
+ _extractData(keys) {
127
+ const output = {id: this.id};
128
+
129
+ for (const key of keys) {
55
130
  if (_.has(this, key)) {
56
131
  _.set(output, key, _.get(this, key));
57
132
  }
@@ -75,20 +150,22 @@ export default class Model {
75
150
  return output;
76
151
  }
77
152
 
78
- toSearchData() {
79
- const indexData = {id: this.id};
80
-
81
- for (const name of this.constructor.searchProperties()) {
82
- indexData[name] = this[name];
83
- }
84
-
85
- return indexData;
86
- }
87
-
153
+ /**
154
+ * Returns the name of the model as a string.
155
+ *
156
+ * @returns {string} - The name of the model class.
157
+ * @static
158
+ */
88
159
  static toString() {
89
- return this['name'];
160
+ return this.name;
90
161
  }
91
162
 
163
+ /**
164
+ * Returns a new required version of the current model class.
165
+ *
166
+ * @returns {this} - A required model subclass.
167
+ * @static
168
+ */
92
169
  static get required() {
93
170
  class Required extends this {
94
171
  static _required = true;
@@ -99,14 +176,35 @@ export default class Model {
99
176
  return Required;
100
177
  }
101
178
 
179
+ /**
180
+ * Returns a list of properties that are indexed.
181
+ *
182
+ * @returns {Array<string>} - The indexed properties.
183
+ * @abstract
184
+ * @static
185
+ */
102
186
  static indexedProperties() {
103
187
  return [];
104
188
  }
105
189
 
190
+ /**
191
+ * Returns a list of properties used for search.
192
+ *
193
+ * @returns {Array<string>} - The search properties.
194
+ * @abstract
195
+ * @static
196
+ */
106
197
  static searchProperties() {
107
198
  return [];
108
199
  }
109
200
 
201
+ /**
202
+ * Creates a model instance from raw data.
203
+ *
204
+ * @param {Object} data - The data to populate the model instance with.
205
+ * @returns {Model} - The populated model instance.
206
+ * @static
207
+ */
110
208
  static fromData(data) {
111
209
  const model = new this();
112
210
 
@@ -129,6 +227,13 @@ export default class Model {
129
227
  return model;
130
228
  }
131
229
 
230
+ /**
231
+ * Determines if a given object is a model instance.
232
+ *
233
+ * @param {Object} possibleModel - The object to check.
234
+ * @returns {boolean} - Returns `true` if the object is a model instance.
235
+ * @static
236
+ */
132
237
  static isModel(possibleModel) {
133
238
  return (
134
239
  possibleModel?.prototype instanceof Model ||
@@ -136,14 +241,24 @@ export default class Model {
136
241
  );
137
242
  }
138
243
 
244
+ /**
245
+ * Determines if a given object is a dry model (a simplified object with an ID).
246
+ *
247
+ * @param {Object} possibleDryModel - The object to check.
248
+ * @returns {boolean} - Returns `true` if the object is a valid dry model.
249
+ * @static
250
+ */
139
251
  static isDryModel(possibleDryModel) {
140
252
  try {
141
253
  return (
254
+ !this.isModel(possibleDryModel) &&
142
255
  Object.keys(possibleDryModel).includes('id') &&
143
- !!possibleDryModel.id.match(/[A-Za-z]+\/[A-Z0-9]+/)
256
+ new RegExp(/[A-Za-z]+\/[A-Z0-9]+/).test(possibleDryModel.id)
144
257
  );
145
- } catch (_) {
258
+ } catch (_error) {
146
259
  return false;
147
260
  }
148
261
  }
149
262
  }
263
+
264
+ export default Model;
package/src/type/Type.js CHANGED
@@ -1,33 +1,67 @@
1
1
  /**
2
+ * Base class for all data types.
3
+ *
4
+ * The `Type` class is a foundational class used to define various data types.
5
+ * It contains common properties and methods that are inherited by more specific types like strings, numbers, and booleans.
6
+ *
2
7
  * @class Type
3
- * @property {string} _type
4
- * @property {boolean} _required
5
- * @property {boolean} _resolved
6
- * @property {map?} _properties
7
- * @property {map?} _items
8
- * @property {map?} _schema
9
8
  */
10
- export default class Type {
9
+ class Type {
10
+ /**
11
+ * @static
12
+ * @property {boolean} _required - Indicates if the type is required. Default is `false`.
13
+ */
11
14
  static _required = false;
15
+
16
+ /**
17
+ * @static
18
+ * @property {boolean} _resolved - Indicates if the type has been resolved. Default is `false`.
19
+ */
12
20
  static _resolved = false;
21
+
22
+ /**
23
+ * @static
24
+ * @property {*} _properties - Properties for defining schemas. Default is `undefined`.
25
+ */
13
26
  static _properties = undefined;
27
+
28
+ /**
29
+ * @static
30
+ * @property {*} _items - Represents items in array types or collections. Default is `undefined`.
31
+ */
14
32
  static _items = undefined;
33
+
34
+ /**
35
+ * @static
36
+ * @property {*} _schema - The schema definition for the type. Default is `undefined`.
37
+ */
15
38
  static _schema = undefined;
16
39
 
40
+ /**
41
+ * Converts the class name to a string, removing the "Type" suffix.
42
+ *
43
+ * @returns {string} The name of the type without the "Type" suffix.
44
+ */
17
45
  static toString() {
18
46
  return this.name?.replace(/Type$/, '');
19
47
  }
20
48
 
21
49
  /**
22
- * @return {Type}
50
+ * Returns a version of the type marked as required.
51
+ *
52
+ * @type {Type}
53
+ * @returns {Type} A subclass of the current type with `_required` set to `true`.
23
54
  */
24
55
  static get required() {
25
56
  class Required extends this {
26
57
  static _required = true;
27
58
  }
28
59
 
60
+ // Define the class name as "Required<OriginalTypeName>"
29
61
  Object.defineProperty(Required, 'name', {value: `Required${this.toString()}Type`});
30
62
 
31
63
  return Required;
32
64
  }
33
65
  }
66
+
67
+ export default Type;
@@ -1,19 +1,70 @@
1
1
  import Type from '../Type.js';
2
2
 
3
- export default class ArrayType {
3
+ /**
4
+ * Represents an array type definition, allowing the specification of an array of a certain type.
5
+ * This class is used to create type definitions for arrays that can be validated and used in schemas.
6
+ *
7
+ * @class ArrayType
8
+ */
9
+ class ArrayType {
10
+ /**
11
+ * Creates a new type definition for an array of the specified type.
12
+ *
13
+ * The `of` method defines an array where the items must be of the specified type. It returns a
14
+ * class representing this array type, which can further be marked as required using the `required` getter.
15
+ *
16
+ * @param {Type} type - The type of the items that the array will contain.
17
+ * @returns {Type} A new class representing an array of the specified type.
18
+ *
19
+ * @example
20
+ * const arrayOfStrings = ArrayType.of(StringType);
21
+ * const requiredArrayOfNumbers = ArrayType.of(NumberType).required;
22
+ */
4
23
  static of(type) {
24
+ /**
25
+ * @class ArrayOf
26
+ * @extends Type
27
+ * Represents an array of a specific type.
28
+ */
5
29
  class ArrayOf extends Type {
30
+ /** @type {string} The data type, which is 'array' */
6
31
  static _type = 'array';
32
+
33
+ /** @type {Type} The type of items contained in the array */
7
34
  static _items = type;
8
35
 
36
+ /**
37
+ * Returns the string representation of the array type.
38
+ *
39
+ * @returns {string} The string representation of the array type.
40
+ */
9
41
  static toString() {
10
42
  return `ArrayOf(${type.toString()})`;
11
43
  }
12
44
 
45
+ /**
46
+ * Marks the array type as required.
47
+ *
48
+ * @returns {Type} A new class representing a required array of the specified type.
49
+ *
50
+ * @example
51
+ * const requiredArrayOfStrings = ArrayType.of(StringType).required;
52
+ */
13
53
  static get required() {
54
+ /**
55
+ * @class RequiredArrayOf
56
+ * @extends ArrayOf
57
+ * Represents a required array of a specific type.
58
+ */
14
59
  class Required extends this {
60
+ /** @type {boolean} Indicates that the array is required */
15
61
  static _required = true;
16
62
 
63
+ /**
64
+ * Returns the string representation of the required array type.
65
+ *
66
+ * @returns {string} The string representation of the required array type.
67
+ */
17
68
  static toString() {
18
69
  return `RequiredArrayOf(${type})`;
19
70
  }
@@ -30,3 +81,5 @@ export default class ArrayType {
30
81
  return ArrayOf;
31
82
  }
32
83
  }
84
+
85
+ export default ArrayType;
@@ -1,15 +1,49 @@
1
1
  import Type from '../Type.js';
2
2
  import ajv from 'ajv';
3
3
 
4
- export default class CustomType {
4
+ /**
5
+ * Represents a custom type definition, allowing the specification of a type based on a given schema.
6
+ * This class uses AJV (Another JSON Schema Validator) to validate schemas and create type definitions.
7
+ *
8
+ * @class CustomType
9
+ */
10
+ class CustomType {
11
+ /**
12
+ * Creates a new custom type definition based on the provided JSON schema.
13
+ *
14
+ * The `of` method allows defining a custom object type using a JSON schema. It validates the schema
15
+ * using AJV to ensure correctness and returns a class representing the custom type.
16
+ *
17
+ * @param {Object} schema - The JSON schema that defines the structure and validation rules for the custom type.
18
+ * @returns {Type} A new class representing the custom type based on the provided schema.
19
+ *
20
+ * @example
21
+ * const customSchema = {
22
+ * type: 'object',
23
+ * properties: { name: { type: 'string' }, age: { type: 'number' } },
24
+ * required: ['name'],
25
+ * };
26
+ * const CustomModel = CustomType.of(customSchema);
27
+ */
5
28
  static of(schema) {
29
+ // Compiles and validates the schema using AJV
6
30
  new ajv().compile(schema);
7
31
 
32
+ /**
33
+ * @class Custom
34
+ * @extends Type
35
+ * Represents a custom type defined by a JSON schema.
36
+ */
8
37
  class Custom extends Type {
38
+ /** @type {string} The data type, which is 'object' */
9
39
  static _type = 'object';
40
+
41
+ /** @type {Object} The JSON schema that defines the structure and validation rules */
10
42
  static _schema = schema;
11
43
  }
12
44
 
13
45
  return Custom;
14
46
  }
15
47
  }
48
+
49
+ export default CustomType;
@@ -1,14 +1,50 @@
1
1
  import Type from '../Type.js';
2
2
 
3
- export default class ResolvedType extends Type {
3
+ /**
4
+ * Class representing a resolved type.
5
+ *
6
+ * The `ResolvedType` class extends the base `Type` class and marks the type as resolved.
7
+ * It provides additional functionality for resolving types and allows creating resolved types based on properties.
8
+ *
9
+ * @class ResolvedType
10
+ * @extends Type
11
+ */
12
+ class ResolvedType extends Type {
13
+ /**
14
+ * @static
15
+ * @property {boolean} _resolved - Indicates if the type is resolved. Always set to `true` for this class.
16
+ */
4
17
  static _resolved = true;
5
18
 
19
+ /**
20
+ * Resolves the type based on the provided model.
21
+ *
22
+ * This method should be overridden in subclasses to provide specific resolution logic.
23
+ * Throws an error if not implemented.
24
+ *
25
+ * @param {*} _model - The model used to resolve the type.
26
+ * @throws {Error} If the method is not implemented in a subclass.
27
+ */
6
28
  static resolve(_model) {
7
29
  throw new Error(`${this.name} does not implement resolve(model)`);
8
30
  }
9
31
 
32
+ /**
33
+ * Creates a subclass of `ResolvedType` that is based on the provided property.
34
+ *
35
+ * The returned class inherits from `ResolvedType` and customizes its `toString` method
36
+ * to reflect the resolved property.
37
+ *
38
+ * @param {*} property - The property to base the resolved type on.
39
+ * @returns {ResolvedType} A subclass of `ResolvedType` customized for the provided property.
40
+ */
10
41
  static of(property) {
11
42
  class ResolvedTypeOf extends ResolvedType {
43
+ /**
44
+ * Converts the resolved type to a string, displaying the resolved property.
45
+ *
46
+ * @returns {string} A string representing the resolved type, including the property.
47
+ */
12
48
  static toString() {
13
49
  return `ResolvedTypeOf(${property})`;
14
50
  }
@@ -17,3 +53,5 @@ export default class ResolvedType extends Type {
17
53
  return ResolvedTypeOf;
18
54
  }
19
55
  }
56
+
57
+ export default ResolvedType;
@@ -1,15 +1,53 @@
1
1
  import ResolvedType from './ResolvedType.js';
2
2
  import slugify from 'slugify';
3
3
 
4
- export default class SlugType extends ResolvedType {
4
+ /**
5
+ * Class representing a slug type.
6
+ *
7
+ * The `SlugType` class extends the `ResolvedType` and provides functionality for generating
8
+ * slugified strings based on a specified property of a model. It allows for the creation of
9
+ * types that resolve into slugs from specific properties.
10
+ *
11
+ * @class SlugType
12
+ * @extends ResolvedType
13
+ */
14
+ class SlugType extends ResolvedType {
15
+ /**
16
+ * Creates a subclass of `ResolvedType` that generates slugs based on the provided property.
17
+ *
18
+ * The returned class inherits from `ResolvedType` and resolves the property into a slugified
19
+ * string using the `slugify` function. It also customizes the `toString` method to reflect
20
+ * the resolved property.
21
+ *
22
+ * @param {string} property - The property to base the slug on.
23
+ * @returns {ResolvedType} A subclass of `ResolvedType` that generates slugs from the provided property.
24
+ */
5
25
  static of(property) {
6
26
  class SlugOf extends ResolvedType {
27
+ /**
28
+ * @static
29
+ * @property {string} _type - The type of the resolved value, always set to 'string' for slug types.
30
+ */
7
31
  static _type = 'string';
8
32
 
33
+ /**
34
+ * Converts the slug type to a string, displaying the resolved property.
35
+ *
36
+ * @returns {string} A string representing the slug type, including the property.
37
+ */
9
38
  static toString() {
10
39
  return `SlugOf(${property})`;
11
40
  }
12
41
 
42
+ /**
43
+ * Resolves the slug from the given model by extracting the specified property and slugifying it.
44
+ *
45
+ * If the specified property in the model is not a string, an empty string is returned.
46
+ * Uses the `slugify` function to convert the property value into a slug (lowercase, hyphen-separated).
47
+ *
48
+ * @param {Object} model - The model from which to extract and slugify the property.
49
+ * @returns {string} The slugified version of the model's property, or an empty string if not valid.
50
+ */
13
51
  static resolve(model) {
14
52
  if (typeof model?.[property] !== 'string') return '';
15
53
 
@@ -22,3 +60,5 @@ export default class SlugType extends ResolvedType {
22
60
  return SlugOf;
23
61
  }
24
62
  }
63
+
64
+ export default SlugType;
@@ -1,5 +1,20 @@
1
1
  import SimpleType from './SimpleType.js';
2
2
 
3
- export default class BooleanType extends SimpleType {
3
+ /**
4
+ * Class representing a boolean type.
5
+ *
6
+ * This class is used to define and handle data of the boolean type.
7
+ * It extends the {@link SimpleType} class to represent string-specific behavior.
8
+ *
9
+ * @class BooleanType
10
+ * @extends SimpleType
11
+ */
12
+ class BooleanType extends SimpleType {
13
+ /**
14
+ * @static
15
+ * @property {string} _type - The type identifier for BooleanType, set to `'boolean'`.
16
+ */
4
17
  static _type = 'boolean';
5
18
  }
19
+
20
+ export default BooleanType;
@@ -1,10 +1,37 @@
1
1
  import SimpleType from './SimpleType.js';
2
2
 
3
- export default class DateType extends SimpleType {
3
+ /**
4
+ * Class representing a date type with ISO date-time format.
5
+ *
6
+ * This class is used to define and handle data of the date type.
7
+ * It extends the {@link SimpleType} class to represent string-specific behavior.
8
+ *
9
+ * @class DateType
10
+ * @extends SimpleType
11
+ */
12
+ class DateType extends SimpleType {
13
+ /**
14
+ * @static
15
+ * @property {string} _type - The type identifier for DateType, set to `'string'`.
16
+ */
4
17
  static _type = 'string';
18
+
19
+ /**
20
+ * @static
21
+ * @property {string} _format - The format for DateType, set to `'iso-date-time'`.
22
+ */
5
23
  static _format = 'iso-date-time';
6
24
 
25
+ /**
26
+ * Checks if the given value is a valid date.
27
+ *
28
+ * @static
29
+ * @param {*} possibleDate - The value to check for a valid date.
30
+ * @returns {boolean} Returns `true` if the value is a valid date or a date string, otherwise `false`.
31
+ */
7
32
  static isDate(possibleDate) {
8
33
  return possibleDate instanceof Date || !isNaN(new Date(possibleDate));
9
34
  }
10
35
  }
36
+
37
+ export default DateType;
@@ -1,5 +1,20 @@
1
1
  import SimpleType from './SimpleType.js';
2
2
 
3
- export default class NumberType extends SimpleType {
3
+ /**
4
+ * Class representing a number type.
5
+ *
6
+ * This class is used to define and handle data of the number type.
7
+ * It extends the {@link SimpleType} class to represent string-specific behavior.
8
+ *
9
+ * @class NumberType
10
+ * @extends SimpleType
11
+ */
12
+ class NumberType extends SimpleType {
13
+ /**
14
+ * @static
15
+ * @property {string} _type - The type identifier for NumberType, set to `'number'`.
16
+ */
4
17
  static _type = 'number';
5
18
  }
19
+
20
+ export default NumberType;
@@ -1,4 +1,14 @@
1
1
  import Type from '../Type.js';
2
2
 
3
- export default class SimpleType extends Type {
3
+ /**
4
+ * Class representing a simple type.
5
+ *
6
+ * This serves as a base class for primitive or simple types such as string, number, or boolean.
7
+ *
8
+ * @class SimpleType
9
+ * @extends Type
10
+ */
11
+ class SimpleType extends Type {
4
12
  }
13
+
14
+ export default SimpleType;
@@ -1,5 +1,20 @@
1
1
  import SimpleType from './SimpleType.js';
2
2
 
3
- export default class StringType extends SimpleType {
3
+ /**
4
+ * Class representing a string type.
5
+ *
6
+ * This class is used to define and handle data of the string type.
7
+ * It extends the {@link SimpleType} class to represent string-specific behavior.
8
+ *
9
+ * @class StringType
10
+ * @extends SimpleType
11
+ */
12
+ class StringType extends SimpleType {
13
+ /**
14
+ * @static
15
+ * @property {string} _type - The type identifier for the string type.
16
+ */
4
17
  static _type = 'string';
5
18
  }
19
+
20
+ export default StringType;