@acodeninja/persist 3.0.0-next.10 → 3.0.0-next.12

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acodeninja/persist",
3
- "version": "3.0.0-next.10",
3
+ "version": "3.0.0-next.12",
4
4
  "description": "A JSON based data modelling and persistence module with alternate storage mechanisms.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -0,0 +1,49 @@
1
+ import lunr from 'lunr';
2
+
3
+ export default class SearchIndex {
4
+ #index;
5
+ #model;
6
+ #compiledIndex;
7
+
8
+ constructor(model, index) {
9
+ this.#index = index;
10
+ this.#model = model;
11
+ if (model.searchProperties().length === 0) {
12
+ throw new NoIndexAvailableSearchIndexError(this.#model);
13
+ }
14
+ }
15
+
16
+ search(query) {
17
+ return (this.#compiledIndex ?? this.#compileIndex()).search(query).map(doc => ({
18
+ score: doc.score,
19
+ model: this.#model.fromData(this.#index[doc.ref]),
20
+ }));
21
+ }
22
+
23
+ #compileIndex() {
24
+ const model = this.#model;
25
+ const index = this.#index;
26
+ this.#compiledIndex = lunr(function () {
27
+ this.ref('id');
28
+
29
+ for (const field of model.searchProperties()) {
30
+ this.field(field);
31
+ }
32
+
33
+ Object.values(index).forEach(function (doc) {
34
+ this.add(doc);
35
+ }, this);
36
+ });
37
+
38
+ return this.#compiledIndex;
39
+ }
40
+ }
41
+
42
+ export class SearchIndexError extends Error {
43
+ }
44
+
45
+ export class NoIndexAvailableSearchIndexError extends SearchIndexError {
46
+ constructor(model) {
47
+ super(`The model ${model.name} has no search properties`);
48
+ }
49
+ }
@@ -163,9 +163,9 @@ export default class StorageEngine {
163
163
  .map(async ([constructor, updatableModels]) => [
164
164
  constructor,
165
165
  await Promise.all(updatableModels.map(async m => {
166
- const currentModel = modelCache[m.id] ?? await this.get(m.id);
167
- modelCache[currentModel.id] = currentModel;
168
- return currentModel;
166
+ const upToDateModel = modelCache[m.id] ?? await this.get(m.id);
167
+ modelCache[upToDateModel.id] = upToDateModel;
168
+ return upToDateModel;
169
169
  })),
170
170
  ]),
171
171
  ))).flat(1)
@@ -193,8 +193,8 @@ export default class StorageEngine {
193
193
  }),
194
194
  );
195
195
 
196
- for (const model of modelsToProcess) {
197
- await processModel(model);
196
+ for (const modelToBeProcessed of modelsToProcess) {
197
+ await processModel(modelToBeProcessed);
198
198
  }
199
199
  };
200
200