@acodeninja/persist 2.2.0 → 2.2.2

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.
@@ -0,0 +1,10 @@
1
+ version = 1
2
+
3
+ [[analyzers]]
4
+ name = "javascript"
5
+
6
+ [analyzers.meta]
7
+ environment = [
8
+ "nodejs",
9
+ "browser"
10
+ ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acodeninja/persist",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
4
4
  "description": "A JSON based data modelling and persistence module with alternate storage mechanisms.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -26,6 +26,7 @@
26
26
  "ajv": "^8.16.0",
27
27
  "ajv-errors": "^3.0.0",
28
28
  "ajv-formats": "^3.0.1",
29
+ "lodash": "^4.17.21",
29
30
  "lunr": "^2.3.9",
30
31
  "slugify": "^1.6.6",
31
32
  "ulid": "^2.3.0"
@@ -43,7 +44,6 @@
43
44
  "eslint": "^9.6.0",
44
45
  "globals": "^15.8.0",
45
46
  "husky": "^9.1.1",
46
- "lodash": "^4.17.21",
47
47
  "monocart-coverage-reports": "^2.10.2",
48
48
  "semantic-release": "^24.0.0",
49
49
  "sinon": "^18.0.0"
package/src/Persist.js CHANGED
@@ -4,7 +4,7 @@ import enableTransactions from './Transactions.js';
4
4
  /**
5
5
  * @class Persist
6
6
  */
7
- export default class Persist {
7
+ class Persist {
8
8
  static _engine = {};
9
9
  /**
10
10
  * @memberof Persist
@@ -42,3 +42,5 @@ export default class Persist {
42
42
  engine.configure(configuration);
43
43
  }
44
44
  }
45
+
46
+ export default Persist;
package/src/Query.js CHANGED
@@ -1,39 +1,60 @@
1
1
  /**
2
- * persist query language features:
3
- * - value match {title: 'test'} or {title: {$is: 'test'}}
4
- * - contains match {list: {$contains: 'test'}} or {string: {$contains: 'es'}}
5
- * - nested query {list: {$contains: {slug: 'test'}}}
6
- * - deep nesting queries {list: {$contains: {string: {$contains: 'test'}}}}
7
- */
8
-
9
- /**
10
- * @class Query
2
+ * The `Query` class is responsible for executing searches on an indexed dataset
3
+ * based on a structured query. It supports various query types including value matches,
4
+ * contains matches, and nested queries.
5
+ *
6
+ * @example
7
+ * // The object has the property `title` witch exactly equals `test`.
8
+ * const query = new Query({title: 'test'});
9
+ * const query = new Query({title: {$is: 'test'}});
10
+ *
11
+ * // The object has the property `list` witch contains the string `test`.
12
+ * const query = new Query({list: {$contains: 'test'}});
13
+ *
14
+ * // The object has the property `string` witch contains the string `es`.
15
+ * const query = new Query({string: {$contains: 'es'}});
16
+ *
17
+ * // The object has the property `list` contains an object
18
+ * // with a property `string` that contains the string `test`.
19
+ * const query = new Query({
20
+ * list: {
21
+ * $contains: {
22
+ * string: {
23
+ * $contains: 'test'
24
+ * }
25
+ * }
26
+ * }
27
+ * });
11
28
  */
12
29
  class Query {
30
+ /**
31
+ * The query object that defines the search criteria.
32
+ * @type {Object}
33
+ */
13
34
  query;
14
35
 
15
36
  /**
37
+ * Constructs a new `Query` instance with the provided query object.
16
38
  *
17
- * @param {object} query
39
+ * @param {Object} query - The structured query object defining the search criteria.
18
40
  */
19
41
  constructor(query) {
20
42
  this.query = query;
21
43
  }
22
44
 
23
45
  /**
24
- * Using the input query, find records in an index that match
46
+ * Executes the query against a model's index and returns the matching results.
25
47
  *
26
- * @param {typeof Model} model
27
- * @param {object} index
48
+ * @param {Model.constructor} model - The model class that contains the `fromData` method for constructing models from data.
49
+ * @param {Object<string, Model>} index - The index dataset to search through.
50
+ * @returns {Array<Model>} The models that match the query.
28
51
  */
29
52
  execute(model, index) {
30
- const matchIs = (query) => !!query?.$is;
53
+ const matchIs = (query) => query?.$is !== undefined;
31
54
  const matchPrimitive = (query) => ['string', 'number', 'boolean'].includes(typeof query);
32
55
  const matchContains = (query) => !!query?.$contains;
33
56
 
34
57
  const matchesQuery = (subject, inputQuery = this.query) => {
35
- if (!subject || !inputQuery) return false;
36
-
37
58
  if (matchPrimitive(inputQuery)) return subject === inputQuery;
38
59
 
39
60
  if (matchIs(inputQuery))
@@ -4,13 +4,21 @@ import ajvErrors from 'ajv-errors';
4
4
  import ajvFormats from 'ajv-formats';
5
5
 
6
6
  /**
7
- * @class SchemaCompiler
7
+ * A class responsible for compiling raw schema definitions into a format that can be validated using the AJV (Another JSON Validator) library.
8
8
  */
9
- export default class SchemaCompiler {
9
+ class SchemaCompiler {
10
10
  /**
11
- * @method compile
12
- * @param {Model|object} rawSchema
13
- * @return {CompiledSchema}
11
+ * Compiles a raw schema into a validation-ready schema, and returns a class that extends `CompiledSchema`.
12
+ *
13
+ * This method converts a given schema into a JSON schema-like format, setting up properties, types, formats, and validation rules.
14
+ * It uses AJV for the validation process and integrates with model types and their specific validation rules.
15
+ *
16
+ * @param {Object|Model} rawSchema - The raw schema or model definition to be compiled.
17
+ * @returns {CompiledSchema} - A class that extends `CompiledSchema`, with the compiled schema and validator attached.
18
+ *
19
+ * @example
20
+ * const schemaClass = SchemaCompiler.compile(MyModelSchema);
21
+ * const isValid = schemaClass.validate(data); // Throws ValidationError if data is invalid.
14
22
  */
15
23
  static compile(rawSchema) {
16
24
  const validation = new ajv({allErrors: true});
@@ -27,7 +35,7 @@ export default class SchemaCompiler {
27
35
 
28
36
  if (Type.Model.isModel(rawSchema)) {
29
37
  schema.required.push('id');
30
- schema.properties['id'] = {type: 'string'};
38
+ schema.properties.id = {type: 'string'};
31
39
  }
32
40
 
33
41
  for (const [name, type] of Object.entries(rawSchema)) {
@@ -88,7 +96,20 @@ export default class SchemaCompiler {
88
96
  }
89
97
 
90
98
  class Schema extends CompiledSchema {
99
+ /**
100
+ * The compiled schema definition.
101
+ * @type {Object}
102
+ * @static
103
+ * @private
104
+ */
91
105
  static _schema = schema;
106
+
107
+ /**
108
+ * The AJV validator function compiled from the schema.
109
+ * @type {Function}
110
+ * @static
111
+ * @private
112
+ */
92
113
  static _validator = validation.compile(schema);
93
114
  }
94
115
 
@@ -96,20 +117,36 @@ export default class SchemaCompiler {
96
117
  }
97
118
  }
98
119
 
120
+
99
121
  /**
100
- * @class CompiledSchema
101
- * @property {object} _schema
102
- * @property {Function} _validator
122
+ * Represents a compiled schema used for validating data models.
123
+ * This class provides a mechanism to validate data using a precompiled schema and a validator function.
103
124
  */
104
125
  export class CompiledSchema {
126
+ /**
127
+ * The schema definition for validation, typically a precompiled JSON schema or similar.
128
+ * @type {?Object}
129
+ * @static
130
+ * @private
131
+ */
105
132
  static _schema = null;
133
+
134
+ /**
135
+ * The validator function used to validate data against the schema.
136
+ * @type {?Function}
137
+ * @static
138
+ * @private
139
+ */
106
140
  static _validator = null;
107
141
 
108
142
  /**
109
- * @method validate
110
- * @param data
111
- * @return {boolean}
112
- * @throws {ValidationError}
143
+ * Validates the given data against the compiled schema.
144
+ *
145
+ * If the data is an instance of a model, it will be converted to a plain object via `toData()` before validation.
146
+ *
147
+ * @param {Object|Model} data - The data or model instance to be validated.
148
+ * @returns {boolean} - Returns `true` if the data is valid according to the schema.
149
+ * @throws {ValidationError} - Throws a `ValidationError` if the data is invalid.
113
150
  */
114
151
  static validate(data) {
115
152
  let inputData = Object.assign({}, data);
@@ -127,15 +164,29 @@ export class CompiledSchema {
127
164
  }
128
165
 
129
166
  /**
130
- * @class ValidationError
131
- * @extends Error
132
- * @property {object[]} errors
133
- * @property {object} data
167
+ * Represents a validation error that occurs when a model or data fails validation.
168
+ * Extends the built-in JavaScript `Error` class.
134
169
  */
135
170
  export class ValidationError extends Error {
171
+ /**
172
+ * Creates an instance of `ValidationError`.
173
+ *
174
+ * @param {Object} data - The data that failed validation.
175
+ * @param {Array<Object>} errors - A list of validation errors, each typically containing details about what failed.
176
+ */
136
177
  constructor(data, errors) {
137
178
  super('Validation failed');
179
+ /**
180
+ * An array of validation errors, containing details about each failed validation.
181
+ * @type {Array<Object>}
182
+ */
138
183
  this.errors = errors;
184
+ /**
185
+ * The data that caused the validation error.
186
+ * @type {Object}
187
+ */
139
188
  this.data = data;
140
189
  }
141
190
  }
191
+
192
+ export default SchemaCompiler;
@@ -3,43 +3,112 @@ import Type from '../type/index.js';
3
3
  import lunr from 'lunr';
4
4
 
5
5
  /**
6
+ * The `Engine` class provides a base interface for implementing data storage and retrieval engines.
7
+ * It includes methods for handling models, indexes, and search functionality.
8
+ *
6
9
  * @class Engine
7
10
  */
8
- export default class Engine {
9
- static _configuration = undefined;
10
-
11
+ class Engine {
12
+ static configuration = undefined;
13
+
14
+ /**
15
+ * Retrieves a model by its ID. This method must be implemented by subclasses.
16
+ *
17
+ * @param {string} _id - The ID of the model to retrieve.
18
+ * @throws {NotImplementedError} Throws if the method is not implemented.
19
+ * @abstract
20
+ */
11
21
  static async getById(_id) {
12
22
  throw new NotImplementedError(`${this.name} must implement .getById()`);
13
23
  }
14
24
 
25
+ /**
26
+ * Saves a model to the data store. This method must be implemented by subclasses.
27
+ *
28
+ * @param {Model} _data - The model data to save.
29
+ * @throws {NotImplementedError} Throws if the method is not implemented.
30
+ * @abstract
31
+ */
15
32
  static async putModel(_data) {
16
33
  throw new NotImplementedError(`${this.name} must implement .putModel()`);
17
34
  }
18
35
 
36
+ /**
37
+ * Retrieves the index for a given model. This method must be implemented by subclasses.
38
+ *
39
+ * @param {Model.constructor} _model - The model to retrieve the index for.
40
+ * @throws {NotImplementedError} Throws if the method is not implemented.
41
+ * @abstract
42
+ */
19
43
  static async getIndex(_model) {
20
44
  throw new NotImplementedError(`${this.name} does not implement .getIndex()`);
21
45
  }
22
46
 
47
+ /**
48
+ * Saves the index for a given model. This method must be implemented by subclasses.
49
+ *
50
+ * @param {Object} _index - The index data to save.
51
+ * @throws {NotImplementedError} Throws if the method is not implemented.
52
+ * @abstract
53
+ */
23
54
  static async putIndex(_index) {
24
55
  throw new NotImplementedError(`${this.name} does not implement .putIndex()`);
25
56
  }
26
57
 
58
+ /**
59
+ * Retrieves the compiled search index for a model. This method must be implemented by subclasses.
60
+ *
61
+ * @param {Model.constructor} _model - The model to retrieve the compiled search index for.
62
+ * @throws {NotImplementedError} Throws if the method is not implemented.
63
+ * @abstract
64
+ */
27
65
  static async getSearchIndexCompiled(_model) {
28
66
  throw new NotImplementedError(`${this.name} does not implement .getSearchIndexCompiled()`);
29
67
  }
30
68
 
69
+ /**
70
+ * Retrieves the raw search index for a model. This method must be implemented by subclasses.
71
+ *
72
+ * @param {Model.constructor} _model - The model to retrieve the raw search index for.
73
+ * @throws {NotImplementedError} Throws if the method is not implemented.
74
+ * @abstract
75
+ */
31
76
  static async getSearchIndexRaw(_model) {
32
77
  throw new NotImplementedError(`${this.name} does not implement .getSearchIndexRaw()`);
33
78
  }
34
79
 
80
+ /**
81
+ * Saves the compiled search index for a model. This method must be implemented by subclasses.
82
+ *
83
+ * @param {Model.constructor} _model - The model for which the compiled search index is saved.
84
+ * @param {Object} _compiledIndex - The compiled search index data.
85
+ * @throws {NotImplementedError} Throws if the method is not implemented.
86
+ * @abstract
87
+ */
35
88
  static async putSearchIndexCompiled(_model, _compiledIndex) {
36
89
  throw new NotImplementedError(`${this.name} does not implement .putSearchIndexCompiled()`);
37
90
  }
38
91
 
92
+ /**
93
+ * Saves the raw search index for a model. This method must be implemented by subclasses.
94
+ *
95
+ * @param {Model.constructor} _model - The model for which the raw search index is saved.
96
+ * @param {Object} _rawIndex - The raw search index data.
97
+ * @throws {NotImplementedError} Throws if the method is not implemented.
98
+ * @abstract
99
+ */
39
100
  static async putSearchIndexRaw(_model, _rawIndex) {
40
101
  throw new NotImplementedError(`${this.name} does not implement .putSearchIndexRaw()`);
41
102
  }
42
103
 
104
+ /**
105
+ * Performs a search query on a model's index and returns the matching models.
106
+ *
107
+ * @param {Model.constructor} model - The model class.
108
+ * @param {object} query - The search query string.
109
+ * @returns {Array<Model>} An array of models matching the search query.
110
+ * @throws {EngineError} Throws if the search index is not available for the model.
111
+ */
43
112
  static async search(model, query) {
44
113
  this.checkConfiguration();
45
114
 
@@ -55,6 +124,7 @@ export default class Engine {
55
124
  for (const result of results) {
56
125
  output.push({
57
126
  ...result,
127
+ score: Number(result.score.toFixed(4)),
58
128
  model: await this.get(model, result.ref),
59
129
  });
60
130
  }
@@ -62,6 +132,13 @@ export default class Engine {
62
132
  return output;
63
133
  }
64
134
 
135
+ /**
136
+ * Finds models that match a query in the model's index.
137
+ *
138
+ * @param {Model.constructor} model - The model class to search.
139
+ * @param {object} query - The query object containing search criteria.
140
+ * @returns {Array<Model>} An array of models matching the query.
141
+ */
65
142
  static async find(model, query) {
66
143
  this.checkConfiguration();
67
144
  const index = await this.getIndex(model);
@@ -69,50 +146,57 @@ export default class Engine {
69
146
  return new Query(query).execute(model, index);
70
147
  }
71
148
 
149
+ /**
150
+ * Stores a model and its associated index data into the system.
151
+ *
152
+ * @param {Model} model - The model to store.
153
+ * @throws {EngineError} Throws if the model fails to validate or index fails to save.
154
+ */
72
155
  static async put(model) {
73
156
  this.checkConfiguration();
74
157
  const uploadedModels = [];
75
158
  const indexUpdates = {};
76
159
 
77
- const processModel = async (model) => {
78
- if (uploadedModels.includes(model.id)) return false;
79
- model.validate();
160
+ const processModel = async (m) => {
161
+ if (!uploadedModels.includes(m.id)) {
162
+ m.validate();
80
163
 
81
- await this.putModel(model);
164
+ await this.putModel(m);
82
165
 
83
- uploadedModels.push(model.id);
84
- indexUpdates[model.constructor.name] = (indexUpdates[model.constructor.name] ?? []).concat([model]);
166
+ uploadedModels.push(m.id);
167
+ indexUpdates[m.constructor.name] = (indexUpdates[m.constructor.name] ?? []).concat([m]);
85
168
 
86
- if (model.constructor.searchProperties().length > 0) {
87
- const rawSearchIndex = {
88
- ...await this.getSearchIndexRaw(model.constructor),
89
- [model.id]: model.toSearchData(),
90
- };
169
+ if (m.constructor.searchProperties().length > 0) {
170
+ const rawSearchIndex = {
171
+ ...await this.getSearchIndexRaw(m.constructor),
172
+ [m.id]: m.toSearchData(),
173
+ };
91
174
 
92
- await this.putSearchIndexRaw(model.constructor, rawSearchIndex);
175
+ await this.putSearchIndexRaw(m.constructor, rawSearchIndex);
93
176
 
94
- const compiledIndex = lunr(function () {
95
- this.ref('id');
177
+ const compiledIndex = lunr(function () {
178
+ this.ref('id');
96
179
 
97
- for (const field of model.constructor.searchProperties()) {
98
- this.field(field);
99
- }
180
+ for (const field of m.constructor.searchProperties()) {
181
+ this.field(field);
182
+ }
100
183
 
101
- Object.values(rawSearchIndex).forEach(function (doc) {
102
- this.add(doc);
103
- }, this);
104
- });
184
+ Object.values(rawSearchIndex).forEach(function (doc) {
185
+ this.add(doc);
186
+ }, this);
187
+ });
105
188
 
106
- await this.putSearchIndexCompiled(model.constructor, compiledIndex);
107
- }
108
-
109
- for (const [_, property] of Object.entries(model)) {
110
- if (Type.Model.isModel(property)) {
111
- await processModel(property);
189
+ await this.putSearchIndexCompiled(m.constructor, compiledIndex);
112
190
  }
113
- if (Array.isArray(property) && Type.Model.isModel(property[0])) {
114
- for (const subModel of property) {
115
- await processModel(subModel);
191
+
192
+ for (const [_, property] of Object.entries(m)) {
193
+ if (Type.Model.isModel(property)) {
194
+ await processModel(property);
195
+ }
196
+ if (Array.isArray(property) && Type.Model.isModel(property[0])) {
197
+ for (const subModel of property) {
198
+ await processModel(subModel);
199
+ }
116
200
  }
117
201
  }
118
202
  }
@@ -122,6 +206,14 @@ export default class Engine {
122
206
  await this.putIndex(indexUpdates);
123
207
  }
124
208
 
209
+ /**
210
+ * Retrieves a model by its ID and converts it to its data representation.
211
+ *
212
+ * @param {Model.constructor} model - The model class to retrieve.
213
+ * @param {string} id - The ID of the model to retrieve.
214
+ * @returns {Model} The found model.
215
+ * @throws {NotFoundEngineError} Throws if the model is not found.
216
+ */
125
217
  static async get(model, id) {
126
218
  this.checkConfiguration();
127
219
 
@@ -134,6 +226,12 @@ export default class Engine {
134
226
  }
135
227
  }
136
228
 
229
+ /**
230
+ * Hydrates a model by populating its related properties (e.g., submodels) from stored data.
231
+ *
232
+ * @param {Model} model - The model to hydrate.
233
+ * @returns {Model} The hydrated model.
234
+ */
137
235
  static async hydrate(model) {
138
236
  this.checkConfiguration();
139
237
  const hydratedModels = {};
@@ -189,53 +287,122 @@ export default class Engine {
189
287
 
190
288
  function getSubModelClass(modelToProcess, name, isArray = false) {
191
289
  const constructorField = modelToProcess.constructor[name];
290
+
192
291
  if (constructorField instanceof Function && !constructorField.prototype) {
193
292
  return isArray ? constructorField()._items : constructorField();
194
293
  }
294
+
195
295
  return isArray ? constructorField._items : constructorField;
196
296
  }
197
297
 
198
298
  return await hydrateModel(await this.get(model.constructor, model.id));
199
299
  }
200
300
 
301
+ /**
302
+ * Configures the engine with specific settings.
303
+ *
304
+ * @param {Object} configuration - The configuration settings for the engine.
305
+ * @returns {Engine} A new engine instance with the applied configuration.
306
+ */
201
307
  static configure(configuration) {
202
308
  class ConfiguredStore extends this {
203
- static _configuration = configuration;
309
+ static configuration = configuration;
204
310
  }
205
311
 
206
- Object.defineProperty(ConfiguredStore, 'name', {value: `${this.toString()}`});
312
+ Object.defineProperty(ConfiguredStore, 'name', { value: `${this.toString()}` });
207
313
 
208
314
  return ConfiguredStore;
209
315
  }
210
316
 
317
+ /**
318
+ * Checks if the engine is properly configured.
319
+ *
320
+ * @throws {MissConfiguredError} Throws if the engine is misconfigured.
321
+ * @abstract
322
+ */
211
323
  static checkConfiguration() {
212
324
 
213
325
  }
214
326
 
327
+ /**
328
+ * Returns the name of the engine class.
329
+ *
330
+ * @returns {string} The name of the engine class.
331
+ */
215
332
  static toString() {
216
333
  return this.name;
217
334
  }
218
- };
335
+ }
219
336
 
337
+ /**
338
+ * Represents a general error that occurs within the engine.
339
+ * Extends the built-in `Error` class.
340
+ */
220
341
  export class EngineError extends Error {
342
+ /**
343
+ * The underlying error that caused this engine error, if available.
344
+ * @type {Error|undefined}
345
+ */
221
346
  underlyingError;
347
+
348
+ /**
349
+ * Creates an instance of `EngineError`.
350
+ *
351
+ * @param {string} message - The error message.
352
+ * @param {Error} [error] - An optional underlying error that caused this error.
353
+ */
222
354
  constructor(message, error = undefined) {
223
355
  super(message);
224
356
  this.underlyingError = error;
225
357
  }
226
358
  }
227
359
 
360
+ /**
361
+ * Represents an error that occurs when a requested resource or item is not found in the engine.
362
+ * Extends the `EngineError` class.
363
+ */
228
364
  export class NotFoundEngineError extends EngineError {
365
+ /**
366
+ * Creates an instance of `NotFoundEngineError`.
367
+ *
368
+ * @param {string} message - The error message.
369
+ * @param {Error} [error] - An optional underlying error that caused this error.
370
+ */
229
371
  }
230
372
 
373
+ /**
374
+ * Represents an error indicating that a certain method or functionality is not implemented in the engine.
375
+ * Extends the `EngineError` class.
376
+ */
231
377
  export class NotImplementedError extends EngineError {
378
+ /**
379
+ * Creates an instance of `NotImplementedError`.
380
+ *
381
+ * @param {string} message - The error message.
382
+ * @param {Error} [error] - An optional underlying error that caused this error.
383
+ */
232
384
  }
233
385
 
386
+ /**
387
+ * Represents an error indicating that the engine is misconfigured.
388
+ * Extends the `EngineError` class.
389
+ */
234
390
  export class MissConfiguredError extends EngineError {
391
+ /**
392
+ * The configuration that led to the misconfiguration error.
393
+ * @type {Object}
394
+ */
235
395
  configuration;
236
396
 
397
+ /**
398
+ * Creates an instance of `MissConfiguredError`.
399
+ *
400
+ * @param {Object} configuration - The configuration object that caused the misconfiguration.
401
+ */
237
402
  constructor(configuration) {
238
403
  super('Engine is miss-configured');
239
404
  this.configuration = configuration;
240
405
  }
241
406
  }
407
+
408
+ export default Engine;