@acodeninja/persist 3.0.0-next.8 → 3.0.0-next.9

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.8",
3
+ "version": "3.0.0-next.9",
4
4
  "description": "A JSON based data modelling and persistence module with alternate storage mechanisms.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -108,26 +108,118 @@ export default class StorageEngine {
108
108
  }
109
109
 
110
110
  /**
111
- *
111
+ * Delete a model and update indexes that reference it
112
112
  * @param {Type.Model} model
113
113
  * @throws {ModelNotRegisteredStorageEngineError}
114
114
  * @throws {ModelNotFoundStorageEngineError}
115
115
  */
116
116
  async delete(model) {
117
- if (!Object.keys(this.models).includes(model.constructor.name))
118
- throw new ModelNotRegisteredStorageEngineError(model, this);
117
+ const modelsToDelete = [];
118
+ const modelsToPut = [];
119
+ const indexCache = {};
120
+ const indexActions = {};
121
+ const searchIndexCache = {};
122
+ const searchIndexActions = {};
123
+
124
+ const processModel = async (modelToProcess) => {
125
+ if (!Object.keys(this.models).includes(modelToProcess.constructor.name))
126
+ throw new ModelNotRegisteredStorageEngineError(modelToProcess, this);
119
127
 
120
- const currentModel = await this.get(model.id);
128
+ const currentModel = await this.get(model.id);
121
129
 
122
- await this._deleteModel(currentModel.id);
130
+ modelsToDelete.push(currentModel.id);
123
131
 
124
- const currentIndex = this._getIndex(currentModel.constructor);
132
+ const modelToProcessConstructor = this.getModelConstructorFromId(modelToProcess.id);
133
+ indexActions[modelToProcessConstructor] = indexActions[modelToProcessConstructor] ?? [];
134
+ searchIndexActions[modelToProcessConstructor] = searchIndexActions[modelToProcessConstructor] ?? [];
125
135
 
126
- await this._putIndex(currentModel.constructor, _.omit(currentIndex, [currentModel.id]));
136
+ if (currentModel.constructor.indexedPropertiesResolved().length) {
137
+ indexActions[modelToProcessConstructor].push(['delete', modelToProcess]);
138
+ }
127
139
 
128
- const currentSearchIndex = this._getSearchIndex(currentModel.constructor);
140
+ if (currentModel.constructor.searchProperties().length) {
141
+ searchIndexActions[modelToProcessConstructor].push(['delete', modelToProcess]);
142
+ }
129
143
 
130
- await this._putSearchIndex(currentModel.constructor, _.omit(currentSearchIndex, [currentModel.id]));
144
+ const linkedModels = await this.getInstancesLinkedTo(modelToProcess, indexCache);
145
+ const links = this.getLinksFor(modelToProcess.constructor);
146
+ Object.values(Object.fromEntries(await Promise.all(
147
+ Object.entries(linkedModels)
148
+ .map(async ([constructor, updatableModels]) => [
149
+ constructor,
150
+ await Promise.all(updatableModels.map(m => this.get(m.id))),
151
+ ]),
152
+ ))).flat(1)
153
+ .forEach(m =>
154
+ Object.entries(links[m.constructor.name])
155
+ .forEach(([linkName, _]) => {
156
+ m[linkName] = undefined;
157
+ modelsToPut.push(m);
158
+
159
+ const modelToProcessConstructor = this.getModelConstructorFromId(m.id);
160
+ indexActions[modelToProcessConstructor].push(['reindex', m]);
161
+
162
+ if (m.constructor.searchProperties().length) {
163
+ const modelToProcessConstructor = this.getModelConstructorFromId(m.id);
164
+ searchIndexActions[modelToProcessConstructor].push(['reindex', m]);
165
+ }
166
+ }),
167
+ );
168
+ };
169
+
170
+ await processModel(model);
171
+
172
+ await Promise.all([
173
+ Promise.all(Object.entries(indexActions).map(async ([constructorName, actions]) => {
174
+ const modelConstructor = this.models[constructorName];
175
+ indexCache[constructorName] = indexCache[constructorName] ?? await this._getIndex(modelConstructor);
176
+
177
+ actions.forEach(([action, model]) => {
178
+ switch (action) {
179
+ case 'delete':
180
+ indexCache[constructorName] = _.omit(indexCache[constructorName], [model.id]);
181
+ break;
182
+ case 'reindex':
183
+ indexCache[constructorName] = {
184
+ ...indexCache[constructorName],
185
+ [model.id]: model.toIndexData(),
186
+ };
187
+ break;
188
+ }
189
+ });
190
+ })),
191
+ Promise.all(Object.entries(searchIndexActions).map(async ([constructorName, actions]) => {
192
+ const modelConstructor = this.models[constructorName];
193
+ searchIndexCache[constructorName] = searchIndexCache[constructorName] ?? await this._getSearchIndex(modelConstructor);
194
+
195
+ actions.forEach(([action, model]) => {
196
+ switch (action) {
197
+ case 'delete':
198
+ searchIndexCache[constructorName] = _.omit(searchIndexCache[constructorName], [model.id]);
199
+ break;
200
+ case 'reindex':
201
+ searchIndexCache[constructorName] = {
202
+ ...searchIndexCache[constructorName],
203
+ [model.id]: model.toSearchData(),
204
+ };
205
+ break;
206
+ }
207
+ });
208
+ })),
209
+ ]);
210
+
211
+ await Promise.all([
212
+ Promise.all(modelsToDelete.map(m => this._deleteModel(m))),
213
+ Promise.all(modelsToPut.map(m => this._putModel(m))),
214
+ Promise.all(
215
+ Object.entries(indexCache)
216
+ .map(([constructorName, _]) => this._putIndex(this.models[constructorName], indexCache[constructorName])),
217
+ ),
218
+ Promise.all(
219
+ Object.entries(searchIndexCache)
220
+ .map(([constructorName, _]) => this._putSearchIndex(this.models[constructorName], searchIndexCache[constructorName])),
221
+ ),
222
+ ]);
131
223
  }
132
224
 
133
225
  /**
@@ -144,6 +236,36 @@ export default class StorageEngine {
144
236
  return constructor;
145
237
  }
146
238
 
239
+ /**
240
+ * Get model instance that are directly linked to the given model in either direction
241
+ * @param {Type.Model} model
242
+ * @param {object} cache
243
+ * @return {Record<string, Record<string, Type.Model>>}
244
+ */
245
+ async getInstancesLinkedTo(model, cache = {}) {
246
+ return Object.fromEntries(
247
+ Object.entries(
248
+ await Promise.all(
249
+ Object.entries(this.getLinksFor(model.constructor))
250
+ .map(([name, _]) =>
251
+ cache[name] ? Promise.resolve([name, Object.values(cache[name])]) :
252
+ this._getIndex(this.models[name])
253
+ .then(i => {
254
+ cache[name] = i;
255
+ return [name, Object.values(i)];
256
+ }),
257
+ ),
258
+ ).then(Object.fromEntries),
259
+ ).map(([name, i]) => [
260
+ name,
261
+ i.map(i => Object.fromEntries(
262
+ Object.entries(i)
263
+ .filter(([name, property]) => name === 'id' || property?.id === model.id),
264
+ )).filter(i => Object.keys(i).length > 1),
265
+ ]),
266
+ );
267
+ }
268
+
147
269
  /**
148
270
  * Get model classes that are directly linked to the given model in either direction
149
271
  * @param {Type.Model.constructor} model
@@ -171,9 +293,9 @@ export default class StorageEngine {
171
293
  registeredModelName,
172
294
  propertyName,
173
295
  typeof propertyType === 'function' &&
174
- !/^class/.test(Function.prototype.toString.call(propertyType)) &&
175
- !Type.Model.isModel(propertyType) ?
176
- propertyType() : propertyType,
296
+ !/^class/.test(Function.prototype.toString.call(propertyType)) &&
297
+ !Type.Model.isModel(propertyType) ?
298
+ propertyType() : propertyType,
177
299
  ])
178
300
  .filter(([_m, _p, type]) => Type.Model.isModel(type))
179
301
  .map(([containingModel, propertyName, propertyType]) => ({