@fjell/lib-sequelize 4.3.4 → 4.4.1

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.
Files changed (150) hide show
  1. package/dist/cjs/AggregationBuilder.cjs +31 -0
  2. package/dist/cjs/Coordinate.cjs +37 -0
  3. package/dist/cjs/Definition.cjs +46 -0
  4. package/dist/cjs/EventCoordinator.cjs +35 -0
  5. package/dist/cjs/Instance.cjs +40 -0
  6. package/dist/cjs/KeyMaster.cjs +91 -0
  7. package/dist/cjs/Operations.cjs +29 -0
  8. package/dist/cjs/Options.cjs +39 -0
  9. package/dist/cjs/QueryBuilder.cjs +188 -0
  10. package/dist/cjs/ReferenceBuilder.cjs +34 -0
  11. package/dist/cjs/RowProcessor.cjs +41 -0
  12. package/dist/cjs/contained/Instance.cjs +21 -0
  13. package/dist/cjs/contained/index.cjs +10 -0
  14. package/dist/cjs/index.cjs +23 -0
  15. package/dist/cjs/logger.cjs +10 -0
  16. package/dist/cjs/ops/all.cjs +62 -0
  17. package/dist/cjs/ops/create.cjs +23 -0
  18. package/dist/cjs/ops/find.cjs +45 -0
  19. package/dist/cjs/ops/get.cjs +49 -0
  20. package/dist/cjs/ops/one.cjs +26 -0
  21. package/dist/cjs/ops/remove.cjs +72 -0
  22. package/dist/cjs/ops/update.cjs +59 -0
  23. package/dist/cjs/primary/Instance.cjs +31 -0
  24. package/dist/cjs/primary/index.cjs +10 -0
  25. package/dist/cjs/util/general.cjs +52 -0
  26. package/dist/es/AggregationBuilder.js +27 -0
  27. package/dist/es/Coordinate.js +13 -0
  28. package/dist/es/Definition.js +23 -0
  29. package/dist/es/EventCoordinator.js +30 -0
  30. package/dist/es/Instance.js +17 -0
  31. package/dist/es/KeyMaster.js +86 -0
  32. package/dist/es/Operations.js +25 -0
  33. package/dist/es/Options.js +16 -0
  34. package/dist/{src → es}/QueryBuilder.js +67 -46
  35. package/dist/es/ReferenceBuilder.js +30 -0
  36. package/dist/es/RowProcessor.js +37 -0
  37. package/dist/es/contained/Instance.js +17 -0
  38. package/dist/es/contained/index.js +2 -0
  39. package/dist/es/index.js +10 -0
  40. package/dist/es/logger.js +6 -0
  41. package/dist/{src → es}/ops/all.js +25 -14
  42. package/dist/es/ops/create.js +19 -0
  43. package/dist/es/ops/find.js +41 -0
  44. package/dist/es/ops/get.js +45 -0
  45. package/dist/es/ops/one.js +22 -0
  46. package/dist/es/ops/remove.js +68 -0
  47. package/dist/es/ops/update.js +55 -0
  48. package/dist/es/primary/Instance.js +27 -0
  49. package/dist/es/primary/index.js +2 -0
  50. package/dist/es/util/general.js +47 -0
  51. package/dist/index.cjs +810 -0
  52. package/dist/index.cjs.map +1 -0
  53. package/dist/types/AggregationBuilder.d.ts +4 -0
  54. package/dist/{src → types}/Definition.d.ts +2 -2
  55. package/dist/{src → types}/Instance.d.ts +2 -2
  56. package/dist/{src → types}/KeyMaster.d.ts +1 -2
  57. package/dist/{src → types}/Operations.d.ts +4 -4
  58. package/dist/{src → types}/Options.d.ts +15 -4
  59. package/dist/types/ReferenceBuilder.d.ts +3 -0
  60. package/dist/types/RowProcessor.d.ts +5 -0
  61. package/dist/{src → types}/contained/Instance.d.ts +2 -1
  62. package/dist/types/logger.d.ts +2 -0
  63. package/dist/types/ops/all.d.ts +5 -0
  64. package/dist/{src → types}/ops/create.d.ts +5 -4
  65. package/dist/types/ops/find.d.ts +5 -0
  66. package/dist/{src → types}/ops/get.d.ts +2 -1
  67. package/dist/types/ops/one.d.ts +5 -0
  68. package/dist/types/ops/remove.d.ts +5 -0
  69. package/dist/types/ops/update.d.ts +5 -0
  70. package/dist/{src → types}/primary/Instance.d.ts +2 -1
  71. package/dist/types/util/general.d.ts +4 -0
  72. package/package.json +45 -35
  73. package/dist/src/Coordinate.js +0 -7
  74. package/dist/src/Coordinate.js.map +0 -1
  75. package/dist/src/Definition.js +0 -16
  76. package/dist/src/Definition.js.map +0 -1
  77. package/dist/src/EventCoordinator.js +0 -56
  78. package/dist/src/EventCoordinator.js.map +0 -1
  79. package/dist/src/Instance.js +0 -14
  80. package/dist/src/Instance.js.map +0 -1
  81. package/dist/src/KeyMaster.js +0 -58
  82. package/dist/src/KeyMaster.js.map +0 -1
  83. package/dist/src/Operations.js +0 -22
  84. package/dist/src/Operations.js.map +0 -1
  85. package/dist/src/Options.js +0 -16
  86. package/dist/src/Options.js.map +0 -1
  87. package/dist/src/QueryBuilder.js.map +0 -1
  88. package/dist/src/RowProcessor.d.ts +0 -3
  89. package/dist/src/RowProcessor.js +0 -11
  90. package/dist/src/RowProcessor.js.map +0 -1
  91. package/dist/src/contained/Instance.js +0 -14
  92. package/dist/src/contained/Instance.js.map +0 -1
  93. package/dist/src/contained/index.js +0 -2
  94. package/dist/src/contained/index.js.map +0 -1
  95. package/dist/src/index.js +0 -8
  96. package/dist/src/index.js.map +0 -1
  97. package/dist/src/logger.d.ts +0 -2
  98. package/dist/src/logger.js +0 -4
  99. package/dist/src/logger.js.map +0 -1
  100. package/dist/src/ops/all.d.ts +0 -4
  101. package/dist/src/ops/all.js.map +0 -1
  102. package/dist/src/ops/create.js +0 -14
  103. package/dist/src/ops/create.js.map +0 -1
  104. package/dist/src/ops/find.d.ts +0 -4
  105. package/dist/src/ops/find.js +0 -26
  106. package/dist/src/ops/find.js.map +0 -1
  107. package/dist/src/ops/get.js +0 -36
  108. package/dist/src/ops/get.js.map +0 -1
  109. package/dist/src/ops/one.d.ts +0 -4
  110. package/dist/src/ops/one.js +0 -17
  111. package/dist/src/ops/one.js.map +0 -1
  112. package/dist/src/ops/remove.d.ts +0 -5
  113. package/dist/src/ops/remove.js +0 -56
  114. package/dist/src/ops/remove.js.map +0 -1
  115. package/dist/src/ops/update.d.ts +0 -4
  116. package/dist/src/ops/update.js +0 -49
  117. package/dist/src/ops/update.js.map +0 -1
  118. package/dist/src/primary/Instance.js +0 -17
  119. package/dist/src/primary/Instance.js.map +0 -1
  120. package/dist/src/primary/index.js +0 -2
  121. package/dist/src/primary/index.js.map +0 -1
  122. package/eslint.config.mjs +0 -70
  123. package/src/Coordinate.ts +0 -16
  124. package/src/Definition.ts +0 -49
  125. package/src/EventCoordinator.ts +0 -103
  126. package/src/Instance.ts +0 -45
  127. package/src/KeyMaster.ts +0 -90
  128. package/src/Operations.ts +0 -42
  129. package/src/Options.ts +0 -41
  130. package/src/QueryBuilder.ts +0 -208
  131. package/src/RowProcessor.ts +0 -23
  132. package/src/contained/Instance.ts +0 -45
  133. package/src/contained/index.ts +0 -1
  134. package/src/index.ts +0 -7
  135. package/src/logger.ts +0 -5
  136. package/src/ops/all.ts +0 -76
  137. package/src/ops/create.ts +0 -40
  138. package/src/ops/find.ts +0 -49
  139. package/src/ops/get.ts +0 -67
  140. package/src/ops/one.ts +0 -37
  141. package/src/ops/remove.ts +0 -81
  142. package/src/ops/update.ts +0 -78
  143. package/src/primary/Instance.ts +0 -41
  144. package/src/primary/index.ts +0 -1
  145. /package/dist/{src → types}/Coordinate.d.ts +0 -0
  146. /package/dist/{src → types}/EventCoordinator.d.ts +0 -0
  147. /package/dist/{src → types}/QueryBuilder.d.ts +0 -0
  148. /package/dist/{src → types}/contained/index.d.ts +0 -0
  149. /package/dist/{src → types}/index.d.ts +0 -0
  150. /package/dist/{src → types}/primary/index.d.ts +0 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,810 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+
5
+ const Library = require('@fjell/lib');
6
+ const deepmerge = require('deepmerge');
7
+ const Logging = require('@fjell/logging');
8
+ const core = require('@fjell/core');
9
+ const sequelize = require('sequelize');
10
+
11
+ function _interopNamespaceDefault(e) {
12
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
13
+ if (e) {
14
+ for (const k in e) {
15
+ if (k !== 'default') {
16
+ const d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: () => e[k]
20
+ });
21
+ }
22
+ }
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ const Library__namespace = /*#__PURE__*/_interopNamespaceDefault(Library);
29
+
30
+ const SCOPE_SEQUELIZE = 'sequelize';
31
+ const createCoordinate = (kta, scopes)=>{
32
+ const coordinate = Library__namespace.createCoordinate(kta, [
33
+ SCOPE_SEQUELIZE,
34
+ ...scopes || []
35
+ ]);
36
+ return coordinate;
37
+ };
38
+
39
+ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-undefined */ const clean = (obj)=>{
40
+ return Object.fromEntries(Object.entries(obj).filter(([_, v])=>v !== undefined));
41
+ };
42
+ //Recursive implementation of jSON.stringify;
43
+ const general.stringifyJSON = function(obj, visited = new Set()) {
44
+ const arrOfKeyVals = [];
45
+ const arrVals = [];
46
+ let objKeys = [];
47
+ /*********CHECK FOR PRIMITIVE TYPES**********/ if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null) return '' + obj;
48
+ else if (typeof obj === 'string') return '"' + obj + '"';
49
+ /*********DETECT CIRCULAR REFERENCES**********/ if (obj instanceof Object && visited.has(obj)) {
50
+ return '"(circular)"';
51
+ } else if (Array.isArray(obj)) {
52
+ //check for empty array
53
+ if (obj[0] === undefined) return '[]';
54
+ else {
55
+ // Add array to visited before processing its elements
56
+ visited.add(obj);
57
+ obj.forEach(function(el) {
58
+ arrVals.push(general.stringifyJSON(el, visited));
59
+ });
60
+ return '[' + arrVals + ']';
61
+ }
62
+ } else if (obj instanceof Object) {
63
+ // Add object to visited before processing its properties
64
+ visited.add(obj);
65
+ //get object keys
66
+ objKeys = Object.keys(obj);
67
+ //set key output;
68
+ objKeys.forEach(function(key) {
69
+ const keyOut = '"' + key + '":';
70
+ const keyValOut = obj[key];
71
+ //skip functions and undefined properties
72
+ if (keyValOut instanceof Function || keyValOut === undefined) return; // Skip this entry entirely instead of pushing an empty string
73
+ else if (typeof keyValOut === 'string') arrOfKeyVals.push(keyOut + '"' + keyValOut + '"');
74
+ else if (typeof keyValOut === 'boolean' || typeof keyValOut === 'number' || keyValOut === null) arrOfKeyVals.push(keyOut + keyValOut);
75
+ else if (keyValOut instanceof Object) {
76
+ arrOfKeyVals.push(keyOut + general.stringifyJSON(keyValOut, visited));
77
+ }
78
+ });
79
+ return '{' + arrOfKeyVals + '}';
80
+ }
81
+ return '';
82
+ };
83
+
84
+ const DEFAULT_OPTIONS = {
85
+ deleteOnRemove: false,
86
+ references: [],
87
+ aggregations: []
88
+ };
89
+ const createOptions = (libOptions)=>{
90
+ const options = Library__namespace.createOptions(libOptions);
91
+ return deepmerge(DEFAULT_OPTIONS, clean(options));
92
+ };
93
+
94
+ const logger$1.default = Logging.getLogger('@fjell/lib-sequelize');
95
+
96
+ const logger$c = logger$1.default.get('lib-sequelize', 'Definition');
97
+ function createDefinition(kta, scopes, libOptions) {
98
+ logger$c.debug('createDefinition', {
99
+ kta,
100
+ scopes,
101
+ libOptions
102
+ });
103
+ const coordinate = createCoordinate(kta, scopes);
104
+ const options = createOptions(libOptions);
105
+ const definition = Library__namespace.createDefinition(coordinate, options);
106
+ return {
107
+ ...definition,
108
+ options
109
+ };
110
+ }
111
+
112
+ const logger$b = logger$1.default.get('sequelize', 'QueryBuilder');
113
+ const addDeleteQuery = (options, model)=>{
114
+ logger$b.default('Adding Delete Query', {
115
+ options
116
+ });
117
+ if (model.getAttributes().deletedAt) {
118
+ options.where['deletedAt'] = {
119
+ [sequelize.Op.eq]: null
120
+ };
121
+ } else if (model.getAttributes().isDeleted) {
122
+ options.where['isDeleted'] = {
123
+ [sequelize.Op.eq]: false
124
+ };
125
+ }
126
+ return options;
127
+ };
128
+ const addEventQueries = (options, events, model)=>{
129
+ logger$b.default('Adding Event Queries', {
130
+ options,
131
+ events
132
+ });
133
+ Object.keys(events).forEach((key)=>{
134
+ if (!model.getAttributes()[`${key}At`]) {
135
+ throw new Error(`Event ${key} is not supported on this model, column ${key}At not found`);
136
+ }
137
+ let whereClauses = {};
138
+ const event = events[key];
139
+ if (event.start) {
140
+ whereClauses = {
141
+ ...whereClauses,
142
+ [sequelize.Op.gte]: new Date(event.start)
143
+ };
144
+ }
145
+ if (event.end) {
146
+ whereClauses = {
147
+ ...whereClauses,
148
+ [sequelize.Op.lt]: new Date(event.end)
149
+ };
150
+ }
151
+ if (event.by) {
152
+ if (!model.getAttributes()[`${key}By`]) {
153
+ throw new Error(`Event ${key} is not supported on this model, column ${key}By not found`);
154
+ }
155
+ whereClauses = {
156
+ ...whereClauses,
157
+ [sequelize.Op.eq]: event.by
158
+ };
159
+ }
160
+ options.where[`${key}At`] = whereClauses;
161
+ });
162
+ return options;
163
+ };
164
+ // Add the references to the query
165
+ const addReferenceQueries = (options, references, model)=>{
166
+ logger$b.default('Adding Reference Queries', {
167
+ options,
168
+ references
169
+ });
170
+ Object.keys(references).forEach((key)=>{
171
+ logger$b.default('Adding Reference Query', {
172
+ key,
173
+ references
174
+ });
175
+ if (!model.getAttributes()[`${key}Id`]) {
176
+ throw new Error(`Reference ${key} is not supported on this model, column ${key}Id not found`);
177
+ }
178
+ if (core.isPriKey(references[key])) {
179
+ const priKey = references[key];
180
+ options.where[`${key}Id`] = {
181
+ [sequelize.Op.eq]: priKey.pk
182
+ };
183
+ } else if (core.isComKey(references[key])) {
184
+ throw new Error('ComKeys are not supported in Sequelize');
185
+ }
186
+ });
187
+ return options;
188
+ };
189
+ const addCompoundCondition = (options, compoundCondition, model)=>{
190
+ const where = {};
191
+ let compoundOp;
192
+ const compoundType = compoundCondition.compoundType;
193
+ if (compoundType === "AND") {
194
+ compoundOp = sequelize.Op.and;
195
+ } else {
196
+ compoundOp = sequelize.Op.or;
197
+ }
198
+ let conditions = {};
199
+ compoundCondition.conditions.forEach((condition)=>{
200
+ if (core.isCondition(condition)) {
201
+ conditions = addCondition(conditions, condition, model);
202
+ } else {
203
+ throw new Error('Nest Compound conditions not supported');
204
+ }
205
+ });
206
+ where[compoundOp] = conditions;
207
+ options.where = where;
208
+ return options;
209
+ };
210
+ const addCondition = (conditions, condition, model)=>{
211
+ let conditionOp;
212
+ const conditionColumn = condition.column;
213
+ if (!model.getAttributes()[conditionColumn]) {
214
+ throw new Error(`Condition column ${conditionColumn} not found on model ${model.name}`);
215
+ }
216
+ if (condition.operator === '==') {
217
+ conditionOp = sequelize.Op.eq;
218
+ } else if (condition.operator === '<') {
219
+ conditionOp = sequelize.Op.lt;
220
+ } else if (condition.operator === '>') {
221
+ conditionOp = sequelize.Op.gt;
222
+ } else if (condition.operator === '<=') {
223
+ conditionOp = sequelize.Op.lte;
224
+ } else if (condition.operator === '>=') {
225
+ conditionOp = sequelize.Op.gte;
226
+ } else if (condition.operator === 'in') {
227
+ conditionOp = sequelize.Op.in;
228
+ } else {
229
+ throw new Error(`Operator ${condition.operator} not supported`);
230
+ }
231
+ conditions[conditionColumn] = {
232
+ [conditionOp]: condition.value
233
+ };
234
+ return conditions;
235
+ };
236
+ const buildQuery = (itemQuery, model)=>{
237
+ logger$b.default('build', {
238
+ itemQuery
239
+ });
240
+ let options = {
241
+ where: {}
242
+ };
243
+ if (itemQuery.compoundCondition) {
244
+ logger$b.default('Adding Conditions', {
245
+ compoundCondition: itemQuery.compoundCondition
246
+ });
247
+ options = addCompoundCondition(options, itemQuery.compoundCondition, model);
248
+ }
249
+ // If the model has a deletedAt column, we need to add a delete query
250
+ if (model.getAttributes().deletedAt || model.getAttributes().isDeleted) {
251
+ options = addDeleteQuery(options, model);
252
+ }
253
+ if (itemQuery.refs) {
254
+ options = addReferenceQueries(options, itemQuery.refs, model);
255
+ }
256
+ if (itemQuery.events) {
257
+ options = addEventQueries(options, itemQuery.events, model);
258
+ }
259
+ // TODO: Once we start to support Aggs on the server-side, we'll need to parse agg queries
260
+ // Apply a limit to the result set
261
+ if (itemQuery.limit) {
262
+ logger$b.default('Limiting to', {
263
+ limit: itemQuery.limit
264
+ });
265
+ options.limit = itemQuery.limit;
266
+ }
267
+ // Apply an offset to the result set
268
+ if (itemQuery.offset) {
269
+ options.offset = itemQuery.offset;
270
+ }
271
+ // Add orderBy to the query
272
+ if (itemQuery.orderBy) {
273
+ itemQuery.orderBy.forEach((orderBy)=>{
274
+ if (!model.getAttributes()[orderBy.field]) {
275
+ throw new Error(`Order by field ${orderBy.field} not found on model ${model.name}`);
276
+ }
277
+ options.order = [
278
+ [
279
+ orderBy.field,
280
+ orderBy.direction
281
+ ]
282
+ ];
283
+ });
284
+ }
285
+ return options;
286
+ };
287
+
288
+ const logger$a = logger$1.default.get('sequelize', 'KeyMaster');
289
+ const removeKey = (item)=>{
290
+ logger$a.default('Removing Key', {
291
+ item
292
+ });
293
+ delete item.key;
294
+ return item;
295
+ };
296
+ // export const populateKey = <
297
+ // S extends string,
298
+ // L1 extends string = never,
299
+ // L2 extends string = never,
300
+ // L3 extends string = never,
301
+ // L4 extends string = never,
302
+ // L5 extends string = never
303
+ // >(
304
+ // item: ItemProperties<S, L1, L2, L3, L4, L5>,
305
+ // keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>
306
+ // ): ItemProperties<S, L1, L2, L3, L4, L5> => {
307
+ // if (keyTypes.length === 1) {
308
+ // item.key = { kt: keyTypes[0], pk: item.id };
309
+ // delete item.id;
310
+ // } else if (keyTypes.length === 2) {
311
+ // item.key = {
312
+ // kt: keyTypes[0], pk: item.id,
313
+ // // TODO: Shouldn't this be inspecting the model to get the primary key type?
314
+ // loc: [{ kt: keyTypes[1], lk: item[keyTypes[1] + 'Id'] }],
315
+ // };
316
+ // delete item.id;
317
+ // delete item[keyTypes[1] + 'Id'];
318
+ // } else {
319
+ // throw new Error('Not implemented');
320
+ // }
321
+ // return item;
322
+ // }
323
+ const addKey = (item, keyTypes)=>{
324
+ logger$a.default('Adding Key', {
325
+ item
326
+ });
327
+ const key = {};
328
+ if (Array.isArray(keyTypes) && keyTypes.length > 1) {
329
+ const type = [
330
+ ...keyTypes
331
+ ];
332
+ const pkType = type.shift();
333
+ Object.assign(key, {
334
+ kt: pkType,
335
+ pk: item.id
336
+ });
337
+ // TODO: This is really just for primary items
338
+ if (type.length === 1) {
339
+ // TODO: This should be looking at the model to get the primary key of the reference item or association
340
+ const locKeyTypeId = type[0] + 'Id';
341
+ Object.assign(key, {
342
+ loc: [
343
+ {
344
+ kt: type[0],
345
+ lk: item[locKeyTypeId]
346
+ }
347
+ ]
348
+ });
349
+ } else if (type.length === 2) {
350
+ throw new Error('Not implemented');
351
+ } else if (type.length === 3) {
352
+ throw new Error('Not implemented');
353
+ } else if (type.length === 4) {
354
+ throw new Error('Not implemented');
355
+ } else if (type.length === 5) {
356
+ throw new Error('Not implemented');
357
+ }
358
+ } else {
359
+ Object.assign(key, {
360
+ kt: keyTypes[0],
361
+ pk: item.id
362
+ });
363
+ }
364
+ Object.assign(item, {
365
+ key
366
+ });
367
+ return item;
368
+ };
369
+
370
+ const buildReference = async (item, referenceDefinition, registry)=>{
371
+ // Check if there is more than one key type
372
+ if (referenceDefinition.kta.length > 1) {
373
+ throw new Error("The ReferenceBuilder doesn't work with more than one key type yet");
374
+ }
375
+ // Check if dependencies exist
376
+ if (!registry) {
377
+ throw new Error("This model definition has a reference definition, but the registry is not present");
378
+ }
379
+ // Find the Library.Instance for the key type
380
+ const library = registry.get(referenceDefinition.kta);
381
+ if (!library) {
382
+ throw new Error("This model definition has a reference definition, but the dependency is not present");
383
+ }
384
+ // Create a PriKey using the column value from item
385
+ const priKey = {
386
+ kt: referenceDefinition.kta[0],
387
+ pk: item[referenceDefinition.column]
388
+ };
389
+ // Get the referenced item using the Library.Operations get method
390
+ const referencedItem = await library.operations.get(priKey);
391
+ // TODO: In a Fjell-compliant implementation, this value should be stored in the ref property
392
+ // For now, we'll just populate the property directly
393
+ // Store the result in the property on item
394
+ item[referenceDefinition.property] = referencedItem;
395
+ return item;
396
+ };
397
+
398
+ const buildAggregation = async (item, aggregationDefinition, registry)=>{
399
+ const location = core.ikToLKA(item.key);
400
+ // Get the library instance from the registry using the key type array
401
+ const libraryInstance = registry.get(aggregationDefinition.kta);
402
+ if (!libraryInstance) {
403
+ throw new Error(`Library instance not found for key type array: ${aggregationDefinition.kta.join(', ')}`);
404
+ }
405
+ // Based on cardinality, use either one or all operation
406
+ if (aggregationDefinition.cardinality === 'one') {
407
+ // For one-to-one relationship, use the one operation
408
+ return libraryInstance.operations.one({}, location).then((result)=>{
409
+ item[aggregationDefinition.property] = result;
410
+ return item;
411
+ });
412
+ } else {
413
+ // For one-to-many relationship, use the all operation
414
+ return libraryInstance.operations.all({}, location).then((results)=>{
415
+ item[aggregationDefinition.property] = results;
416
+ return item;
417
+ });
418
+ }
419
+ };
420
+
421
+ const logger$9 = logger$1.default.get("sequelize", "EventCoordinator");
422
+ //#endregion
423
+ const populateEvents = (item)=>{
424
+ const events = {
425
+ created: {
426
+ at: item.createdAt || null
427
+ },
428
+ updated: {
429
+ at: item.updatedAt || null
430
+ },
431
+ deleted: {
432
+ at: null
433
+ }
434
+ };
435
+ item.events = events;
436
+ return item;
437
+ };
438
+ const removeEvents = (item)=>{
439
+ logger$9.default('Removing Events', {
440
+ item
441
+ });
442
+ delete item.events;
443
+ return item;
444
+ };
445
+
446
+ const logger$8 = logger$1.default.get('sequelize', 'RowProcessor');
447
+ const processRow = async (row, keyTypes, referenceDefinitions, aggregationDefinitions, registry)=>{
448
+ logger$8.default('Processing Row', {
449
+ row
450
+ });
451
+ let item = row.get({
452
+ plain: true
453
+ });
454
+ logger$8.default('Adding Key to Item with Key Types: %s', general.stringifyJSON(keyTypes));
455
+ item = addKey(item, keyTypes);
456
+ item = populateEvents(item);
457
+ logger$8.default('Key Added to Item: %s', general.stringifyJSON(item.key));
458
+ if (referenceDefinitions && referenceDefinitions.length > 0) {
459
+ for (const referenceDefinition of referenceDefinitions){
460
+ logger$8.default('Processing Reference for %s to %s', item.key.kt, general.stringifyJSON(referenceDefinition.kta));
461
+ item = await buildReference(item, referenceDefinition, registry);
462
+ }
463
+ }
464
+ if (aggregationDefinitions && aggregationDefinitions.length > 0) {
465
+ for (const aggregationDefinition of aggregationDefinitions){
466
+ logger$8.default('Processing Aggregation for %s from %s', item.key.kt, general.stringifyJSON(aggregationDefinition.kta));
467
+ item = await buildAggregation(item, aggregationDefinition, registry);
468
+ }
469
+ }
470
+ logger$8.default('Processed Row: %j', general.stringifyJSON(item));
471
+ return item;
472
+ };
473
+
474
+ const logger$7 = logger$1.default.get('sequelize', 'ops', 'all');
475
+ const all.getAllOperation = (models, definition, registry)=>{
476
+ const { coordinate, options: { references, aggregations } } = definition;
477
+ //#region Query
478
+ const all = async (itemQuery, locations)=>{
479
+ logger$7.default('All', {
480
+ itemQuery,
481
+ locations
482
+ });
483
+ const loc = locations || [];
484
+ // SQ Libs don't support locations
485
+ if (loc.length > 1) {
486
+ throw new Error('Not implemented for more than one location key');
487
+ }
488
+ // We have the model here?
489
+ // @ts-ignore
490
+ const model = models[0];
491
+ // We have the model here?
492
+ const options = buildQuery(itemQuery, model);
493
+ // If this has a location array, we need to add a where clause
494
+ if (loc.length === 1) {
495
+ const locKeyType = loc[0].kt;
496
+ if (model.associations[locKeyType]) {
497
+ const association = model.associations[locKeyType];
498
+ options.where = {
499
+ ...options.where,
500
+ [association.foreignKey]: {
501
+ [sequelize.Op.eq]: loc[0].lk
502
+ }
503
+ };
504
+ } else {
505
+ logger$7.error('Location key type not found in sequelize model association for: %s', locKeyType);
506
+ throw new Error('Location key type not found in model');
507
+ }
508
+ }
509
+ logger$7.default('Configured this Item Query', {
510
+ itemQuery,
511
+ options
512
+ });
513
+ const matchingItems = await model.findAll(options);
514
+ // this.logger.default('Matching Items', { matchingItems });
515
+ // TODO: Move this Up!
516
+ return await Promise.all(matchingItems.map(async (row)=>{
517
+ const processedRow = await processRow(row, coordinate.kta, references, aggregations, registry);
518
+ return core.validateKeys(processedRow, coordinate.kta);
519
+ }));
520
+ };
521
+ return all;
522
+ };
523
+
524
+ const logger$6 = logger$1.default.get('sequelize', 'ops', 'create');
525
+ const getCreateOperation = (// eslint-disable-next-line @typescript-eslint/no-unused-vars
526
+ models, // eslint-disable-next-line @typescript-eslint/no-unused-vars
527
+ definition, // eslint-disable-next-line @typescript-eslint/no-unused-vars
528
+ registry)=>{
529
+ const create = async (item, options)=>{
530
+ logger$6.default('Create', {
531
+ item,
532
+ options
533
+ });
534
+ throw new Error('Not implemented');
535
+ };
536
+ return create;
537
+ };
538
+
539
+ const logger$5 = logger$1.default.get('sequelize', 'ops', 'find');
540
+ const getFindOperation = (models, definition, registry)=>{
541
+ const { options: { finders, references, aggregations } } = definition;
542
+ const find = async (finder, finderParams, locations)=>{
543
+ logger$5.default('Find', {
544
+ finder,
545
+ finderParams,
546
+ locations
547
+ });
548
+ // Note that we execute the createFinders function here because we want to make sure we're always getting the
549
+ // most up to date methods.
550
+ if (finders && finders[finder]) {
551
+ const finderMethod = finders[finder];
552
+ if (finderMethod) {
553
+ const results = await finderMethod(finderParams, locations);
554
+ if (results && results.length > 0) {
555
+ return await Promise.all(results.map(async (row)=>{
556
+ const processedRow = await processRow(row, definition.coordinate.kta, references, aggregations, registry);
557
+ return core.validateKeys(processedRow, definition.coordinate.kta);
558
+ }));
559
+ } else {
560
+ return [];
561
+ }
562
+ } else {
563
+ logger$5.error(`Finder %s not found`, finder);
564
+ throw new Error(`Finder ${finder} not found`);
565
+ }
566
+ } else {
567
+ logger$5.error(`No finders have been defined for this lib`);
568
+ throw new Error(`No finders found`);
569
+ }
570
+ };
571
+ return find;
572
+ };
573
+
574
+ const logger$4 = logger$1.default.get('sequelize', 'ops', 'get');
575
+ const getGetOperation = (models, definition, registry)=>{
576
+ const { coordinate, options: { references, aggregations } } = definition;
577
+ const { kta } = coordinate;
578
+ const get = async (key)=>{
579
+ logger$4.default('Get', {
580
+ key
581
+ });
582
+ if (!core.isValidItemKey(key)) {
583
+ logger$4.error('Key for Get is not a valid ItemKey: %j', key);
584
+ throw new Error('Key for Get is not a valid ItemKey');
585
+ }
586
+ const itemKey = key;
587
+ // @ts-ignore
588
+ const model = models[0];
589
+ let item;
590
+ if (core.isPriKey(itemKey)) {
591
+ item = await model.findByPk(itemKey.pk);
592
+ } else if (core.isComKey(itemKey)) {
593
+ var _comKey_loc_, _comKey_loc_1;
594
+ const comKey = itemKey;
595
+ // TODO: This should probably interrogate the model?
596
+ item = await model.findOne({
597
+ where: {
598
+ id: comKey.pk,
599
+ [(comKey === null || comKey === void 0 ? void 0 : (_comKey_loc_ = comKey.loc[0]) === null || _comKey_loc_ === void 0 ? void 0 : _comKey_loc_.kt) + 'Id']: comKey === null || comKey === void 0 ? void 0 : (_comKey_loc_1 = comKey.loc[0]) === null || _comKey_loc_1 === void 0 ? void 0 : _comKey_loc_1.lk
600
+ }
601
+ });
602
+ }
603
+ if (!item) {
604
+ throw new Library.NotFoundError('get', coordinate, key);
605
+ } else {
606
+ return core.validateKeys(await processRow(item, kta, references, aggregations, registry), kta);
607
+ }
608
+ };
609
+ return get;
610
+ };
611
+
612
+ const logger$3 = logger$1.default.get('sequelize', 'ops', 'one');
613
+ const getOneOperation = (models, definition, registry)=>{
614
+ const one = async (itemQuery, locations = [])=>{
615
+ logger$3.default('One', {
616
+ itemQuery,
617
+ locations
618
+ });
619
+ const items = await all.getAllOperation(models, definition, registry)(itemQuery, locations);
620
+ if (items.length > 0) {
621
+ return items[0];
622
+ } else {
623
+ return null;
624
+ }
625
+ };
626
+ return one;
627
+ };
628
+
629
+ const logger$2 = logger$1.default.get('sequelize', 'ops', 'remove');
630
+ const getRemoveOperation = (models, definition, // eslint-disable-next-line @typescript-eslint/no-unused-vars
631
+ registry)=>{
632
+ const { coordinate, options } = definition;
633
+ const { kta } = coordinate;
634
+ const remove = async (key)=>{
635
+ logger$2.default('Remove', {
636
+ key
637
+ });
638
+ if (!core.isValidItemKey(key)) {
639
+ logger$2.error('Key for Remove is not a valid ItemKey: %j', key);
640
+ throw new Error('Key for Remove is not a valid ItemKey');
641
+ }
642
+ // @ts-ignore
643
+ const model = models[0];
644
+ let item;
645
+ let returnItem;
646
+ logger$2.debug('remove: %s', core.abbrevIK(key));
647
+ if (core.isPriKey(key)) {
648
+ item = await model.findByPk(key.pk);
649
+ } else if (core.isComKey(key)) {
650
+ var _comKey_loc_, _comKey_loc_1;
651
+ const comKey = key;
652
+ item = await model.findOne({
653
+ where: {
654
+ id: comKey.pk,
655
+ [(comKey === null || comKey === void 0 ? void 0 : (_comKey_loc_ = comKey.loc[0]) === null || _comKey_loc_ === void 0 ? void 0 : _comKey_loc_.kt) + 'Id']: comKey === null || comKey === void 0 ? void 0 : (_comKey_loc_1 = comKey.loc[0]) === null || _comKey_loc_1 === void 0 ? void 0 : _comKey_loc_1.lk
656
+ }
657
+ });
658
+ }
659
+ const isDeletedAttribute = model.getAttributes().isDeleted;
660
+ const deletedAtAttribute = model.getAttributes().deletedAt;
661
+ if (isDeletedAttribute || deletedAtAttribute) {
662
+ if (model.getAttributes().isDeleted) {
663
+ item.isDeleted = true;
664
+ }
665
+ if (model.getAttributes().deletedAt) {
666
+ item.deletedAt = new Date();
667
+ }
668
+ // Save the object
669
+ await (item === null || item === void 0 ? void 0 : item.save());
670
+ returnItem = item === null || item === void 0 ? void 0 : item.get({
671
+ plain: true
672
+ });
673
+ returnItem = addKey(returnItem, kta);
674
+ returnItem = populateEvents(returnItem);
675
+ } else if (options.deleteOnRemove) {
676
+ await (item === null || item === void 0 ? void 0 : item.destroy());
677
+ returnItem = item === null || item === void 0 ? void 0 : item.get({
678
+ plain: true
679
+ });
680
+ returnItem = addKey(returnItem, kta);
681
+ returnItem = populateEvents(returnItem);
682
+ } else {
683
+ throw new Error('No deletedAt or isDeleted attribute found in model, and deleteOnRemove is not set');
684
+ }
685
+ return returnItem;
686
+ };
687
+ return remove;
688
+ };
689
+
690
+ const logger$1 = logger$1.default.get('sequelize', 'ops', 'update');
691
+ const getUpdateOperation = (models, definition, registry)=>{
692
+ const { options: { references, aggregations } } = definition;
693
+ const update = async (key, item)=>{
694
+ const { coordinate } = definition;
695
+ const { kta } = coordinate;
696
+ logger$1.debug('update: %s, %j', core.abbrevIK(key), item);
697
+ // Find the object we're updating
698
+ // @ts-ignore
699
+ const model = models[0];
700
+ let response;
701
+ if (core.isPriKey(key)) {
702
+ // Find the model by using the PK
703
+ const priKey = key;
704
+ response = await model.findByPk(priKey.pk);
705
+ } else if (core.isComKey(key)) {
706
+ var _comKey_loc_, _comKey_loc_1;
707
+ const comKey = key;
708
+ // Find the model by using both of the identifiers.
709
+ response = await model.findOne({
710
+ where: {
711
+ [(comKey === null || comKey === void 0 ? void 0 : (_comKey_loc_ = comKey.loc[0]) === null || _comKey_loc_ === void 0 ? void 0 : _comKey_loc_.kt) + 'Id']: comKey === null || comKey === void 0 ? void 0 : (_comKey_loc_1 = comKey.loc[0]) === null || _comKey_loc_1 === void 0 ? void 0 : _comKey_loc_1.lk,
712
+ id: comKey === null || comKey === void 0 ? void 0 : comKey.pk
713
+ }
714
+ });
715
+ }
716
+ if (response) {
717
+ // Remove the key and events
718
+ let updateProps = removeKey(item);
719
+ updateProps = removeEvents(item);
720
+ logger$1.default('Response: %s', general.stringifyJSON(response));
721
+ logger$1.default('Update Properties: %s', general.stringifyJSON(updateProps));
722
+ // Update the object
723
+ response = await response.update(updateProps);
724
+ // Populate the key and events
725
+ const processedItem = await processRow(response, kta, references, aggregations, registry);
726
+ const returnItem = core.validateKeys(processedItem, kta);
727
+ return returnItem;
728
+ } else {
729
+ throw new Library.NotFoundError('update', coordinate, key);
730
+ }
731
+ };
732
+ return update;
733
+ };
734
+
735
+ const createOperations = (models, definition, registry)=>{
736
+ const operations = {};
737
+ operations.all = all.getAllOperation(models, definition, registry);
738
+ operations.one = getOneOperation(models, definition, registry);
739
+ operations.create = getCreateOperation();
740
+ operations.update = getUpdateOperation(models, definition, registry);
741
+ operations.get = getGetOperation(models, definition, registry);
742
+ operations.remove = getRemoveOperation(models, definition);
743
+ operations.find = getFindOperation(models, definition, registry);
744
+ operations.upsert = ()=>{
745
+ throw new Error('Not implemented');
746
+ };
747
+ return operations;
748
+ };
749
+
750
+ function createInstance$2(keyTypes, models, libOptions = {}, scopes = [], registry) {
751
+ const definition = createDefinition(keyTypes, scopes, libOptions);
752
+ const operations = createOperations(models, definition, registry);
753
+ return {
754
+ definition,
755
+ operations: Library__namespace.wrapOperations(operations, definition, registry),
756
+ models,
757
+ registry
758
+ };
759
+ }
760
+
761
+ function createInstance$1(keyTypes, models, libOptions = {}, scopes = [], registry) {
762
+ const definition = createDefinition(keyTypes, scopes, libOptions);
763
+ const operations = createOperations(models, definition, registry);
764
+ return {
765
+ definition,
766
+ operations: Library.Contained.wrapOperations(operations, definition, registry),
767
+ models,
768
+ registry
769
+ };
770
+ }
771
+
772
+ const index$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
773
+ __proto__: null,
774
+ createInstance: createInstance$1
775
+ }, Symbol.toStringTag, { value: 'Module' }));
776
+
777
+ const logger = logger$1.default.get('lib-sequelize', 'primary', 'instance');
778
+ function createInstance(keyType, models, libOptions = {}, scopes = [], registry) {
779
+ logger.debug('createInstance', {
780
+ keyType,
781
+ models,
782
+ libOptions,
783
+ scopes
784
+ });
785
+ const definition = createDefinition([
786
+ keyType
787
+ ], scopes, libOptions);
788
+ const operations = createOperations(models, definition, registry);
789
+ return {
790
+ definition,
791
+ operations: Library.Primary.wrapOperations(operations, definition, registry),
792
+ models,
793
+ registry
794
+ };
795
+ }
796
+
797
+ const index = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
798
+ __proto__: null,
799
+ createInstance
800
+ }, Symbol.toStringTag, { value: 'Module' }));
801
+
802
+ exports.Contained = index$1;
803
+ exports.Primary = index;
804
+ exports.SCOPE_SEQUELIZE = SCOPE_SEQUELIZE;
805
+ exports.createCoordinate = createCoordinate;
806
+ exports.createDefinition = createDefinition;
807
+ exports.createInstance = createInstance$2;
808
+ exports.createOperations = createOperations;
809
+ exports.createOptions = createOptions;
810
+ //# sourceMappingURL=index.cjs.map