dynamo-bao 0.2.12 → 0.3.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.
@@ -413,25 +413,33 @@ const MutationMethods = {
413
413
 
414
414
  // Add iteration keys if model is iterable
415
415
  if (this.iterable) {
416
- const iterationKeys = this._getIterationKeys(primaryId, dyUpdatesToSave);
416
+ const iterationKeys = this._getIterationKeys(
417
+ primaryId,
418
+ dyUpdatesToSave,
419
+ );
417
420
  Object.assign(dyUpdatesToSave, iterationKeys);
418
421
  }
419
422
 
420
423
  // Build the update expression first
421
- const { updateExpression, names, values } =
422
- this._buildUpdateExpression(dyUpdatesToSave);
424
+ const { updateExpression, names, values } = this._buildUpdateExpression(
425
+ dyUpdatesToSave,
426
+ currentItem,
427
+ );
423
428
 
424
429
  // Create the base update params
425
430
  const updateParams = {
426
431
  TableName: this.table,
427
432
  Key: this._getDyKeyForPkSk(this._parsePrimaryId(primaryId)),
428
433
  UpdateExpression: updateExpression,
429
- ExpressionAttributeNames: {
430
- ...names,
431
- },
432
434
  ReturnValues: "ALL_NEW",
433
435
  };
434
436
 
437
+ if (Object.keys(names).length > 0) {
438
+ updateParams.ExpressionAttributeNames = {
439
+ ...names,
440
+ };
441
+ }
442
+
435
443
  if (Object.keys(values).length > 0) {
436
444
  updateParams.ExpressionAttributeValues = {
437
445
  ...values,
@@ -580,7 +588,7 @@ const MutationMethods = {
580
588
  }
581
589
  },
582
590
 
583
- _buildUpdateExpression(dyUpdatesToSave) {
591
+ _buildUpdateExpression(dyUpdatesToSave, currentItem = null) {
584
592
  const names = {};
585
593
  const values = {};
586
594
  const expressions = [];
@@ -604,7 +612,28 @@ const MutationMethods = {
604
612
  fieldValue: null,
605
613
  });
606
614
  } else {
607
- expressions.push(field.getUpdateExpression(fieldName, value));
615
+ // For StringSetField, pass the original value for diffing
616
+ const { StringSetFieldClass } = require("../fields");
617
+ if (field instanceof StringSetFieldClass && currentItem) {
618
+ const originalValue = currentItem._loadedDyData[fieldName];
619
+ const updateExpression = field.getUpdateExpression(
620
+ fieldName,
621
+ value,
622
+ originalValue,
623
+ );
624
+
625
+ // Handle ADD_DELETE operations (multiple operations for the same field)
626
+ if (updateExpression && updateExpression.type === "ADD_DELETE") {
627
+ expressions.push(...updateExpression.operations);
628
+ } else if (updateExpression) {
629
+ expressions.push(updateExpression);
630
+ }
631
+ } else {
632
+ const updateExpression = field.getUpdateExpression(fieldName, value);
633
+ if (updateExpression) {
634
+ expressions.push(updateExpression);
635
+ }
636
+ }
608
637
  }
609
638
  }
610
639
 
@@ -612,6 +641,7 @@ const MutationMethods = {
612
641
  const setExpressions = [];
613
642
  const addExpressions = [];
614
643
  const removeExpressions = [];
644
+ const deleteExpressions = [];
615
645
 
616
646
  expressions.forEach((expression) => {
617
647
  if (expression.type === "SET") {
@@ -620,11 +650,15 @@ const MutationMethods = {
620
650
  addExpressions.push(expression.expression);
621
651
  } else if (expression.type === "REMOVE") {
622
652
  removeExpressions.push(expression.expression);
653
+ } else if (expression.type === "DELETE") {
654
+ deleteExpressions.push(expression.expression);
623
655
  }
624
656
 
625
- names[expression.attrNameKey] = expression.fieldName;
657
+ if (expression.attrNameKey) {
658
+ names[expression.attrNameKey] = expression.fieldName;
659
+ }
626
660
 
627
- if (expression.fieldValue !== null) {
661
+ if (expression.fieldValue !== null && expression.attrValueKey) {
628
662
  values[expression.attrValueKey] = expression.fieldValue;
629
663
  }
630
664
  });
@@ -635,6 +669,8 @@ const MutationMethods = {
635
669
  parts.push(`ADD ${addExpressions.join(", ")}`);
636
670
  if (removeExpressions.length > 0)
637
671
  parts.push(`REMOVE ${removeExpressions.join(", ")}`);
672
+ if (deleteExpressions.length > 0)
673
+ parts.push(`DELETE ${deleteExpressions.join(", ")}`);
638
674
 
639
675
  return {
640
676
  updateExpression: parts.join(" "),
@@ -1,5 +1,5 @@
1
1
  const { defaultLogger: logger } = require("../utils/logger");
2
- const { TtlFieldClass } = require("../fields");
2
+ const { TtlFieldClass, StringSetFieldClass } = require("../fields");
3
3
  const { PrimaryKeyConfig } = require("../model-config");
4
4
  const { ConfigurationError } = require("../exceptions");
5
5
  const {
@@ -141,27 +141,43 @@ const ValidationMethods = {
141
141
  // These will throw errors if the fields don't exist
142
142
  const idxPkField = this._getField(index.pk);
143
143
  const idxSkField = this._getField(index.sk);
144
+
145
+ // StringSetField cannot be indexed
146
+ if (idxPkField instanceof StringSetFieldClass) {
147
+ throw new ConfigurationError(
148
+ `StringSetField '${index.pk}' cannot be used as partition key in index '${indexName}' in ${this.name}`,
149
+ this.name,
150
+ );
151
+ }
152
+ if (idxSkField instanceof StringSetFieldClass) {
153
+ throw new ConfigurationError(
154
+ `StringSetField '${index.sk}' cannot be used as sort key in index '${indexName}' in ${this.name}`,
155
+ this.name,
156
+ );
157
+ }
144
158
  });
145
159
 
146
160
  // Validate iteration configuration
147
- if (this.hasOwnProperty('iterable')) {
148
- if (typeof this.iterable !== 'boolean') {
161
+ if (this.hasOwnProperty("iterable")) {
162
+ if (typeof this.iterable !== "boolean") {
149
163
  throw new ConfigurationError(
150
164
  `iterable must be a boolean in ${this.name}`,
151
- this.name
165
+ this.name,
152
166
  );
153
167
  }
154
-
168
+
155
169
  if (this.iterable) {
156
- if (!this.hasOwnProperty('iterationBuckets')) {
170
+ if (!this.hasOwnProperty("iterationBuckets")) {
157
171
  this.iterationBuckets = 100; // Set default
158
172
  } else {
159
- if (!Number.isInteger(this.iterationBuckets) ||
160
- this.iterationBuckets < 1 ||
161
- this.iterationBuckets > 1000) {
173
+ if (
174
+ !Number.isInteger(this.iterationBuckets) ||
175
+ this.iterationBuckets < 1 ||
176
+ this.iterationBuckets > 1000
177
+ ) {
162
178
  throw new ConfigurationError(
163
179
  `iterationBuckets must be an integer between 1 and 1000 in ${this.name}`,
164
- this.name
180
+ this.name,
165
181
  );
166
182
  }
167
183
  }
@@ -13,6 +13,7 @@ class ModelManager {
13
13
  this._tenantId = null; // Changed from _testId
14
14
  this._tenancyEnabled = false;
15
15
  this._models = new Map();
16
+ this._config = null; // Store config for models to access
16
17
  }
17
18
 
18
19
  static getInstance(tenantId = null) {
@@ -27,16 +28,19 @@ class ModelManager {
27
28
 
28
29
  async init(config = {}) {
29
30
  // Validate tenant requirement
30
- const { TenantContext } = require('./tenant-context');
31
+ const { TenantContext } = require("./tenant-context");
31
32
  TenantContext.validateTenantRequired(config);
32
33
 
34
+ // Store config for models to access
35
+ this._config = config;
36
+
33
37
  const client = new DynamoDBClient({
34
38
  region: config.aws.region,
35
39
  });
36
40
  this._docClient = DynamoDBDocumentClient.from(client);
37
41
  this._tableName = config.db.tableName;
38
42
  this._tenancyEnabled = config.tenancy?.enabled || false;
39
-
43
+
40
44
  // Support both tenantId and testId for backward compatibility
41
45
  this._tenantId = config.tenantId || config.testId || this._tenantId;
42
46
 
@@ -46,6 +50,7 @@ class ModelManager {
46
50
  ModelClass._testId = this._tenantId; // Backward compatibility
47
51
  ModelClass.documentClient = this._docClient;
48
52
  ModelClass.table = this._tableName;
53
+ ModelClass._config = config; // Pass config to models
49
54
  ModelClass._validateConfiguration();
50
55
  }
51
56
 
@@ -88,6 +93,7 @@ class ModelManager {
88
93
  if (this._initialized) {
89
94
  ModelClass.documentClient = this._docClient;
90
95
  ModelClass.table = this._tableName;
96
+ ModelClass._config = this._config; // Pass config to newly registered models
91
97
  ModelClass._validateConfiguration();
92
98
  }
93
99
 
package/src/model.js CHANGED
@@ -233,20 +233,18 @@ class BaoModel {
233
233
  throw new Error(`Model ${this.name} is not configured as iterable`);
234
234
  }
235
235
 
236
- const { batchSize = 100, filter = null, loaderContext = null } = options;
236
+ const { batchSize = 100, filter = null } = options;
237
237
 
238
238
  if (this.iterationBuckets === 1) {
239
239
  yield* this._iterateSingleBucket(null, {
240
240
  batchSize,
241
241
  filter,
242
- loaderContext,
243
242
  });
244
243
  } else {
245
244
  for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
246
245
  yield* this._iterateSingleBucket(bucket, {
247
246
  batchSize,
248
247
  filter,
249
- loaderContext,
250
248
  });
251
249
  }
252
250
  }
@@ -267,7 +265,7 @@ class BaoModel {
267
265
  }
268
266
 
269
267
  static async *_iterateSingleBucket(bucketNum, options = {}) {
270
- const { batchSize = 100, filter = null, loaderContext = null } = options;
268
+ const { batchSize = 100, filter = null } = options;
271
269
  const tenantId = this.manager.getTenantId();
272
270
 
273
271
  let iterPk;
@@ -324,7 +322,7 @@ class BaoModel {
324
322
  (item) => item[ITERATION_SK_FIELD],
325
323
  );
326
324
 
327
- const { items } = await this.batchFind(objectIds, loaderContext);
325
+ const { items } = await this.batchFind(objectIds);
328
326
  const batch = Object.values(items);
329
327
 
330
328
  if (batch.length > 0) {
@@ -619,7 +617,7 @@ class BaoModel {
619
617
  * @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
620
618
  * @returns {Promise<Object>} Returns a promise that resolves to the loaded item.
621
619
  */
622
- async getOrLoadRelatedField(fieldName, loaderContext = null) {
620
+ async getOrLoadRelatedField(fieldName) {
623
621
  if (this._relatedObjects[fieldName]) {
624
622
  return this._relatedObjects[fieldName];
625
623
  }
@@ -636,9 +634,7 @@ class BaoModel {
636
634
  if (!value) return null;
637
635
 
638
636
  const ModelClass = this.constructor.manager.getModel(field.modelName);
639
- this._relatedObjects[fieldName] = await ModelClass.find(value, {
640
- loaderContext,
641
- });
637
+ this._relatedObjects[fieldName] = await ModelClass.find(value);
642
638
  return this._relatedObjects[fieldName];
643
639
  }
644
640
 
@@ -646,10 +642,9 @@ class BaoModel {
646
642
  * @description
647
643
  * Load objects for RelatedField's on the current model instance.
648
644
  * @param {string[]} [fieldNames] - The names of the fields to load. If not provided, all related fields will be loaded.
649
- * @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
650
645
  * @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
651
646
  */
652
- async loadRelatedData(fieldNames = null, loaderContext = null) {
647
+ async loadRelatedData(fieldNames = null) {
653
648
  const promises = [];
654
649
 
655
650
  for (const [fieldName, field] of Object.entries(this.constructor.fields)) {
@@ -659,11 +654,9 @@ class BaoModel {
659
654
 
660
655
  if (field instanceof RelatedFieldClass && this[fieldName]) {
661
656
  promises.push(
662
- this._loadRelatedField(fieldName, field, loaderContext).then(
663
- (instance) => {
664
- this._relatedObjects[fieldName] = instance;
665
- },
666
- ),
657
+ this._loadRelatedField(fieldName, field).then((instance) => {
658
+ this._relatedObjects[fieldName] = instance;
659
+ }),
667
660
  );
668
661
  }
669
662
  }
@@ -672,7 +665,7 @@ class BaoModel {
672
665
  return this;
673
666
  }
674
667
 
675
- async _loadRelatedField(fieldName, field, loaderContext = null) {
668
+ async _loadRelatedField(fieldName, field) {
676
669
  const value = this[fieldName];
677
670
  if (!value) return null;
678
671
 
@@ -683,7 +676,7 @@ class BaoModel {
683
676
  }
684
677
 
685
678
  // Load the instance and track its capacity
686
- const relatedInstance = await ModelClass.find(value, { loaderContext });
679
+ const relatedInstance = await ModelClass.find(value);
687
680
 
688
681
  return relatedInstance;
689
682
  }
@@ -711,14 +704,9 @@ class BaoModel {
711
704
  * to find an object.
712
705
  * @param {string} constraintName - The name of the unique constraint to use.
713
706
  * @param {string} value - The value of the unique constraint.
714
- * @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
715
707
  * @returns {Promise<Object>} Returns a promise that resolves to the found item.
716
708
  */
717
- static async findByUniqueConstraint(
718
- constraintName,
719
- value,
720
- loaderContext = null,
721
- ) {
709
+ static async findByUniqueConstraint(constraintName, value) {
722
710
  const constraint = this.uniqueConstraints[constraintName];
723
711
  if (!constraint) {
724
712
  throw new ConfigurationError(
@@ -757,7 +745,7 @@ class BaoModel {
757
745
  return new ObjectNotFound(result.ConsumedCapacity);
758
746
  }
759
747
 
760
- const item = await this.find(result.Item.relatedId, { loaderContext });
748
+ const item = await this.find(result.Item.relatedId);
761
749
 
762
750
  if (item.exists()) {
763
751
  item._addConsumedCapacity(result.ConsumedCapacity, "read");