dynamo-bao 0.3.0 → 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.
package/README.md CHANGED
@@ -24,6 +24,7 @@ DynamoBao is the tool I wish I had when I started.
24
24
  - Return total read/write consumed capacity (even when multiple operations were performed)
25
25
  - Easily iterate over all items in a model for batch processing or migrations
26
26
  - ESM (ECMAScript Modules) support for modern JavaScript projects
27
+ - StringSetField for storing sets of strings with efficient diffing on save
27
28
 
28
29
  ## Requirements
29
30
 
@@ -291,6 +292,8 @@ DynamoBao makes it easy to iterate over all items in a model, which is useful fo
291
292
 
292
293
  By default, all models are created with `iterable: true`. This automatically sets up a dedicated index that allows you to use the `iterateAll()` method on the model class.
293
294
 
295
+ #### Basic Usage
296
+
294
297
  ```javascript
295
298
  // Iterate over all posts, 100 at a time
296
299
  for await (const batch of Post.iterateAll({ batchSize: 100 })) {
@@ -300,6 +303,78 @@ for await (const batch of Post.iterateAll({ batchSize: 100 })) {
300
303
  }
301
304
  ```
302
305
 
306
+ #### Processing Items in Batches
307
+
308
+ ```javascript
309
+ // Process users in smaller batches for better memory management
310
+ for await (const batch of User.iterateAll({ batchSize: 50 })) {
311
+ // Process each batch
312
+ const activeUsers = batch.filter((user) => user.status === "active");
313
+
314
+ // Perform batch operations
315
+ await Promise.all(
316
+ activeUsers.map(async (user) => {
317
+ // Update user or perform other operations
318
+ console.log(`Processing user: ${user.name}`);
319
+ }),
320
+ );
321
+ }
322
+ ```
323
+
324
+ #### Data Migration Example
325
+
326
+ ```javascript
327
+ // Migrate all users to add a new field
328
+ let processedCount = 0;
329
+ for await (const batch of User.iterateAll({ batchSize: 25 })) {
330
+ const updates = batch.map(async (user) => {
331
+ // Only update if the field is missing
332
+ if (!user.hasOwnProperty("newField")) {
333
+ user.newField = "default_value";
334
+ await user.save();
335
+ processedCount++;
336
+ }
337
+ });
338
+
339
+ await Promise.all(updates);
340
+ console.log(`Processed ${processedCount} users so far...`);
341
+ }
342
+ console.log(`Migration complete! Updated ${processedCount} users`);
343
+ ```
344
+
345
+ #### Collecting Results
346
+
347
+ ```javascript
348
+ // Collect all items into an array (be careful with large datasets)
349
+ const allUsers = [];
350
+ for await (const batch of User.iterateAll({ batchSize: 100 })) {
351
+ allUsers.push(...batch);
352
+ }
353
+
354
+ console.log(`Found ${allUsers.length} total users`);
355
+ ```
356
+
357
+ #### Error Handling
358
+
359
+ ```javascript
360
+ // Handle errors when iterating over large datasets
361
+ try {
362
+ for await (const batch of User.iterateAll({ batchSize: 50 })) {
363
+ for (const user of batch) {
364
+ try {
365
+ // Process individual user
366
+ await processUser(user);
367
+ } catch (error) {
368
+ console.error(`Error processing user ${user.userId}:`, error);
369
+ // Continue with other users
370
+ }
371
+ }
372
+ }
373
+ } catch (error) {
374
+ console.error("Critical error during iteration:", error);
375
+ }
376
+ ```
377
+
303
378
  **Cost and Performance**
304
379
 
305
380
  This convenience comes at a cost: every `create`, `update`, or `delete` operation on an iterable model requires a second write to the database to maintain the iteration index. This doubles the write cost for every item.
@@ -319,6 +394,13 @@ models:
319
394
  # ...
320
395
  ```
321
396
 
397
+ **Important Notes**
398
+
399
+ - Models must have `iterable: true` (the default) to use `iterateAll()`
400
+ - Iteration respects tenant context in multi-tenant applications
401
+ - The method returns an async iterator, so you must use `for await` loops
402
+ - If a model is not iterable, calling `iterateAll()` will throw an error
403
+
322
404
  ## Installation / Quick Start
323
405
 
324
406
  Make sure you have [AWS credentials setup in your environment](https://medium.com/@simonazhangzy/installing-and-configuring-the-aws-cli-7d33796e4a7c). You'll also need [node and npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) installed.
@@ -521,3 +603,141 @@ It's worth noting that you didn't have to:
521
603
  - Install a database (either locally or on a server)
522
604
  - Understand how to generate keys and indexes using single table design princples
523
605
  - Manually configure transactions and items to support unique constraints
606
+
607
+ ## Finding Objects with the find Method
608
+
609
+ The `find` method is used to retrieve objects by their primary key. It's important to understand that `find` always returns an object, and you must use the `exists()` method to check if the object was actually found.
610
+
611
+ ### Basic Usage (Single Primary Key)
612
+
613
+ For models with a single primary key field:
614
+
615
+ ```javascript
616
+ const user = await User.find("user123");
617
+
618
+ // Always check if the object exists
619
+ if (user.exists()) {
620
+ console.log("User found:", user.name);
621
+ } else {
622
+ console.log("User not found");
623
+ }
624
+ ```
625
+
626
+ ### Composite Primary Keys
627
+
628
+ For models with composite primary keys (partition key + sort key), you have several options:
629
+
630
+ #### Option 1: Using makePrimaryId (Recommended)
631
+
632
+ ```javascript
633
+ // Model with composite key: appId (partition) + entityId (sort)
634
+ const primaryId = CompositeModel.makePrimaryId("my-app", "entity-123");
635
+ const item = await CompositeModel.find(primaryId);
636
+
637
+ if (item.exists()) {
638
+ console.log("Item found:", item.data);
639
+ } else {
640
+ console.log("Item not found");
641
+ }
642
+ ```
643
+
644
+ #### Option 2: Using Object Notation
645
+
646
+ ```javascript
647
+ // Alternative: pass an object with the key fields
648
+ const item = await CompositeModel.find({
649
+ appId: "my-app",
650
+ entityId: "entity-123",
651
+ });
652
+
653
+ if (item.exists()) {
654
+ console.log("Item found:", item.data);
655
+ } else {
656
+ console.log("Item not found");
657
+ }
658
+ ```
659
+
660
+ ### Working with getPrimaryId()
661
+
662
+ Once you have an object, you can get its primary ID to use with other operations:
663
+
664
+ ```javascript
665
+ const user = await User.create({
666
+ name: "John Doe",
667
+ email: "john@example.com",
668
+ });
669
+
670
+ // Get the primary ID
671
+ const primaryId = user.getPrimaryId();
672
+ console.log("Primary ID:", primaryId);
673
+
674
+ // Use it to find the same object later
675
+ const foundUser = await User.find(primaryId);
676
+ if (foundUser.exists()) {
677
+ console.log("Found user:", foundUser.name);
678
+ }
679
+ ```
680
+
681
+ ### Error Handling Patterns
682
+
683
+ ```javascript
684
+ // Good: Always check exists() before using the object
685
+ const user = await User.find("user123");
686
+ if (user.exists()) {
687
+ console.log("User email:", user.email);
688
+ // Safe to access properties
689
+ } else {
690
+ console.log("User not found - handle appropriately");
691
+ }
692
+
693
+ // Bad: Don't assume the object exists
694
+ const user = await User.find("user123");
695
+ console.log(user.email); // This could be undefined!
696
+ ```
697
+
698
+ ### Batch Finding
699
+
700
+ For loading multiple objects efficiently:
701
+
702
+ ```javascript
703
+ // Load multiple users at once
704
+ const userIds = ["user1", "user2", "user3"];
705
+ const result = await User.batchFind(userIds);
706
+
707
+ // Check each result
708
+ Object.entries(result.items).forEach(([id, user]) => {
709
+ if (user.exists()) {
710
+ console.log(`User ${id}: ${user.name}`);
711
+ } else {
712
+ console.log(`User ${id}: not found`);
713
+ }
714
+ });
715
+ ```
716
+
717
+ ### Using find with Unique Constraints
718
+
719
+ For unique constraint lookups, use the generated methods:
720
+
721
+ ```javascript
722
+ // Find by unique email constraint
723
+ const user = await User.findByEmail("john@example.com");
724
+ if (user.exists()) {
725
+ console.log("User found by email:", user.name);
726
+ } else {
727
+ console.log("No user with that email");
728
+ }
729
+
730
+ // Or use the generic method
731
+ const user = await User.findByUniqueConstraint(
732
+ "uniqueEmail",
733
+ "john@example.com",
734
+ );
735
+ ```
736
+
737
+ ### Key Points to Remember
738
+
739
+ 1. **Always use `exists()`**: The `find` method returns an object even when nothing is found
740
+ 2. **Composite keys**: Use `makePrimaryId()` for composite primary keys
741
+ 3. **Primary IDs**: Use `getPrimaryId()` to get the correct identifier for an object
742
+ 4. **Batch operations**: Use `batchFind()` for loading multiple objects efficiently
743
+ 5. **Unique constraints**: Use the generated `findByX()` methods for unique constraint lookups
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
package/src/fields.js CHANGED
@@ -776,6 +776,230 @@ class TtlField extends DateTimeField {
776
776
  }
777
777
  }
778
778
 
779
+ /**
780
+ * @class StringSetField
781
+ * @memberof BaoFields
782
+ * @description
783
+ * A field that stores a set of string values. Behind the scenes this is backed by a DynamoDB string set.
784
+ * This field cannot be indexed but can be used in filter expressions.
785
+ */
786
+ class StringSetField extends BaoBaseField {
787
+ constructor(options = {}) {
788
+ super(options);
789
+ this.maxStringLength = options.maxStringLength;
790
+ this.maxMemberCount = options.maxMemberCount;
791
+ }
792
+
793
+ validate(value) {
794
+ super.validate(value);
795
+
796
+ if (value === null || value === undefined) {
797
+ return true; // Allow null/undefined
798
+ }
799
+
800
+ // Accept both Set and Array, but prefer Set
801
+ let setToValidate;
802
+ if (value instanceof Set) {
803
+ setToValidate = value;
804
+ } else if (Array.isArray(value)) {
805
+ setToValidate = new Set(value);
806
+ } else {
807
+ throw new ValidationError(
808
+ "StringSetField value must be a Set or Array",
809
+ null,
810
+ value,
811
+ );
812
+ }
813
+
814
+ // Validate member count
815
+ if (this.maxMemberCount && setToValidate.size > this.maxMemberCount) {
816
+ throw new ValidationError(
817
+ `StringSet exceeds maximum member count of ${this.maxMemberCount}`,
818
+ null,
819
+ value,
820
+ );
821
+ }
822
+
823
+ // Validate each string in the set
824
+ for (const item of setToValidate) {
825
+ if (typeof item !== "string") {
826
+ throw new ValidationError(
827
+ "StringSetField can only contain string values",
828
+ null,
829
+ value,
830
+ );
831
+ }
832
+
833
+ if (this.maxStringLength && item.length > this.maxStringLength) {
834
+ throw new ValidationError(
835
+ `String in set exceeds maximum length of ${this.maxStringLength}`,
836
+ null,
837
+ value,
838
+ );
839
+ }
840
+ }
841
+
842
+ return true;
843
+ }
844
+
845
+ getInitialValue() {
846
+ return new Set();
847
+ }
848
+
849
+ toDy(value) {
850
+ if (value === undefined) return undefined;
851
+ if (value === null) return null;
852
+
853
+ // Handle filter values (strings, numbers, objects) - pass through as-is
854
+ if (
855
+ typeof value === "string" ||
856
+ typeof value === "number" ||
857
+ (typeof value === "object" &&
858
+ !Array.isArray(value) &&
859
+ !(value instanceof Set))
860
+ ) {
861
+ return value;
862
+ }
863
+
864
+ // Convert Set or Array to array for DynamoDB
865
+ let arrayValue;
866
+ if (value instanceof Set) {
867
+ arrayValue = Array.from(value);
868
+ } else if (Array.isArray(value)) {
869
+ arrayValue = [...new Set(value)]; // Remove duplicates
870
+ } else {
871
+ throw new ValidationError(
872
+ "StringSetField value must be a Set or Array",
873
+ null,
874
+ value,
875
+ );
876
+ }
877
+
878
+ // Empty sets are stored as null in DynamoDB
879
+ if (arrayValue.length === 0) {
880
+ return null;
881
+ }
882
+
883
+ return arrayValue;
884
+ }
885
+
886
+ fromDy(value) {
887
+ if (value === undefined || value === null) {
888
+ return new Set(); // Return empty Set for missing or null values
889
+ }
890
+
891
+ if (Array.isArray(value)) {
892
+ return new Set(value);
893
+ }
894
+
895
+ return new Set();
896
+ }
897
+
898
+ toGsi(value) {
899
+ throw new ValidationError(
900
+ "StringSetField does not support GSI conversion (sets cannot be indexed)",
901
+ null,
902
+ value,
903
+ );
904
+ }
905
+
906
+ getUpdateExpression(fieldName, value, originalValue) {
907
+ if (value === undefined) return null;
908
+
909
+ const attributeName = `#${fieldName}`;
910
+ const valueAttributeKey = `:${fieldName}`;
911
+
912
+ // Handle null case (remove entire field)
913
+ if (value === null) {
914
+ return {
915
+ type: "REMOVE",
916
+ expression: `${attributeName}`,
917
+ attrNameKey: attributeName,
918
+ attrValueKey: null,
919
+ fieldName: fieldName,
920
+ fieldValue: null,
921
+ };
922
+ }
923
+
924
+ // Convert values to Arrays for DynamoDB (value is already in DynamoDB format from toDy)
925
+ const newArray = Array.isArray(value) ? value : [value];
926
+ const oldArray =
927
+ originalValue && Array.isArray(originalValue) ? originalValue : [];
928
+
929
+ // If no original value or original was empty, use SET
930
+ if (!originalValue || oldArray.length === 0) {
931
+ return {
932
+ type: "SET",
933
+ expression: `${attributeName} = ${valueAttributeKey}`,
934
+ attrNameKey: attributeName,
935
+ attrValueKey: valueAttributeKey,
936
+ fieldName: fieldName,
937
+ fieldValue: newArray,
938
+ };
939
+ }
940
+
941
+ // Convert to Sets for efficient comparison
942
+ const newSet = new Set(newArray);
943
+ const oldSet = new Set(oldArray);
944
+
945
+ // Find items to add and delete
946
+ const toAdd = newArray.filter((item) => !oldSet.has(item));
947
+ const toDelete = oldArray.filter((item) => !newSet.has(item));
948
+
949
+ // If no changes, return null
950
+ if (toAdd.length === 0 && toDelete.length === 0) {
951
+ return null;
952
+ }
953
+
954
+ // Handle mixed ADD and DELETE operations
955
+ // For mixed operations, we use SET which replaces the entire set
956
+ if (toAdd.length > 0 && toDelete.length > 0) {
957
+ return {
958
+ type: "SET",
959
+ expression: `${attributeName} = ${valueAttributeKey}`,
960
+ attrNameKey: attributeName,
961
+ attrValueKey: valueAttributeKey,
962
+ fieldName: fieldName,
963
+ fieldValue: newArray,
964
+ };
965
+ }
966
+
967
+ // If only additions, use ADD
968
+ if (toAdd.length > 0 && toDelete.length === 0) {
969
+ return {
970
+ type: "ADD",
971
+ expression: `${attributeName} ${valueAttributeKey}`,
972
+ attrNameKey: attributeName,
973
+ attrValueKey: valueAttributeKey,
974
+ fieldName: fieldName,
975
+ fieldValue: toAdd,
976
+ };
977
+ }
978
+
979
+ // If only deletions, use DELETE
980
+ if (toDelete.length > 0 && toAdd.length === 0) {
981
+ return {
982
+ type: "DELETE",
983
+ expression: `${attributeName} ${valueAttributeKey}`,
984
+ attrNameKey: attributeName,
985
+ attrValueKey: valueAttributeKey,
986
+ fieldName: fieldName,
987
+ fieldValue: toDelete,
988
+ };
989
+ }
990
+
991
+ // This shouldn't happen, but fallback to SET for safety
992
+ return {
993
+ type: "SET",
994
+ expression: `${attributeName} = ${valueAttributeKey}`,
995
+ attrNameKey: attributeName,
996
+ attrValueKey: valueAttributeKey,
997
+ fieldName: fieldName,
998
+ fieldValue: newArray,
999
+ };
1000
+ }
1001
+ }
1002
+
779
1003
  // Factory functions for creating field instances
780
1004
  const createStringField = (options) => new StringField(options);
781
1005
  const createDateTimeField = (options) => new DateTimeField(options);
@@ -791,6 +1015,7 @@ const createBinaryField = (options) => new BinaryField(options);
791
1015
  const createVersionField = (options) => new VersionField(options);
792
1016
  const createBooleanField = (options) => new BooleanField(options);
793
1017
  const createTtlField = (options) => new TtlField(options);
1018
+ const createStringSetField = (options) => new StringSetField(options);
794
1019
 
795
1020
  // Export both the factory functions and the classes
796
1021
  module.exports = {
@@ -808,6 +1033,7 @@ module.exports = {
808
1033
  VersionField: createVersionField,
809
1034
  BooleanField: createBooleanField,
810
1035
  TtlField: createTtlField,
1036
+ StringSetField: createStringSetField,
811
1037
 
812
1038
  // Classes (for instanceof checks)
813
1039
  StringFieldClass: StringField,
@@ -823,4 +1049,5 @@ module.exports = {
823
1049
  VersionFieldClass: VersionField,
824
1050
  BooleanFieldClass: BooleanField,
825
1051
  TtlFieldClass: TtlField,
1052
+ StringSetFieldClass: StringSetField,
826
1053
  };
@@ -41,26 +41,26 @@ class FilterExpressionBuilder {
41
41
  // Build expression for a single comparison
42
42
  buildComparison(fieldName, operator, value, model) {
43
43
  const nameKey = this.generateName(fieldName);
44
- const convertedValue = this.convertValue(value, model, fieldName);
45
44
 
46
45
  switch (operator) {
47
46
  case "$eq":
47
+ const convertedValue = this.convertValue(value, model, fieldName);
48
48
  const valueKey = this.generateValue(convertedValue);
49
49
  return `${nameKey} = ${valueKey}`;
50
50
  case "$ne":
51
- return `${nameKey} <> ${this.generateValue(convertedValue)}`;
51
+ return `${nameKey} <> ${this.generateValue(this.convertValue(value, model, fieldName))}`;
52
52
  case "$gt":
53
- return `${nameKey} > ${this.generateValue(convertedValue)}`;
53
+ return `${nameKey} > ${this.generateValue(this.convertValue(value, model, fieldName))}`;
54
54
  case "$gte":
55
- return `${nameKey} >= ${this.generateValue(convertedValue)}`;
55
+ return `${nameKey} >= ${this.generateValue(this.convertValue(value, model, fieldName))}`;
56
56
  case "$lt":
57
- return `${nameKey} < ${this.generateValue(convertedValue)}`;
57
+ return `${nameKey} < ${this.generateValue(this.convertValue(value, model, fieldName))}`;
58
58
  case "$lte":
59
- return `${nameKey} <= ${this.generateValue(convertedValue)}`;
59
+ return `${nameKey} <= ${this.generateValue(this.convertValue(value, model, fieldName))}`;
60
60
  case "$contains":
61
- return `contains(${nameKey}, ${this.generateValue(convertedValue)})`;
61
+ return `contains(${nameKey}, ${this.generateValue(this.convertValue(value, model, fieldName))})`;
62
62
  case "$beginsWith":
63
- return `begins_with(${nameKey}, ${this.generateValue(convertedValue)})`;
63
+ return `begins_with(${nameKey}, ${this.generateValue(this.convertValue(value, model, fieldName))})`;
64
64
  case "$in":
65
65
  if (!Array.isArray(value)) {
66
66
  throw new ValidationError("$in operator requires an array value");
@@ -76,6 +76,51 @@ class FilterExpressionBuilder {
76
76
  return value
77
77
  ? `attribute_exists(${nameKey})`
78
78
  : `attribute_not_exists(${nameKey})`;
79
+ case "$size":
80
+ // Handle size comparisons: { $size: 5 } or { $size: { $gt: 2 } }
81
+ if (typeof value === "number") {
82
+ // Direct size comparison
83
+ return `size(${nameKey}) = ${this.generateValue(value)}`;
84
+ } else if (typeof value === "object" && value !== null) {
85
+ // Size comparison with operators
86
+ const sizeOperators = Object.keys(value);
87
+ if (sizeOperators.length !== 1) {
88
+ throw new ValidationError(
89
+ "$size operator with object value must have exactly one comparison operator",
90
+ );
91
+ }
92
+ const sizeOp = sizeOperators[0];
93
+ const sizeValue = value[sizeOp];
94
+
95
+ if (typeof sizeValue !== "number") {
96
+ throw new ValidationError(
97
+ "$size operator requires a numeric value",
98
+ );
99
+ }
100
+
101
+ switch (sizeOp) {
102
+ case "$eq":
103
+ return `size(${nameKey}) = ${this.generateValue(sizeValue)}`;
104
+ case "$ne":
105
+ return `size(${nameKey}) <> ${this.generateValue(sizeValue)}`;
106
+ case "$gt":
107
+ return `size(${nameKey}) > ${this.generateValue(sizeValue)}`;
108
+ case "$gte":
109
+ return `size(${nameKey}) >= ${this.generateValue(sizeValue)}`;
110
+ case "$lt":
111
+ return `size(${nameKey}) < ${this.generateValue(sizeValue)}`;
112
+ case "$lte":
113
+ return `size(${nameKey}) <= ${this.generateValue(sizeValue)}`;
114
+ default:
115
+ throw new ValidationError(
116
+ `Unsupported size comparison operator: ${sizeOp}`,
117
+ );
118
+ }
119
+ } else {
120
+ throw new ValidationError(
121
+ "$size operator requires a number or object with comparison operators",
122
+ );
123
+ }
79
124
  default:
80
125
  throw new QueryError(`Unsupported operator: ${operator}`);
81
126
  }
@@ -151,6 +196,7 @@ class FilterExpressionBuilder {
151
196
  * - Simple field comparisons: { fieldName: value } for exact matches
152
197
  * - Comparison operators: { fieldName: { $eq: value, $ne: value, $gt: value, $gte: value, $lt: value, $lte: value } }
153
198
  * - String operators: { fieldName: { $beginsWith: value, $contains: value } }
199
+ * - Collection operators: { fieldName: { $size: value } } for sets, lists, or maps
154
200
  * - Logical operators:
155
201
  * - $and: [{condition1}, {condition2}] - All conditions must match
156
202
  * - $or: [{condition1}, {condition2}] - At least one condition must match
@@ -170,6 +216,10 @@ class FilterExpressionBuilder {
170
216
  * }
171
217
  *
172
218
  * filterExp4 = {
219
+ * tags: { $size: { $gt: 2 } }, // Set/list size greater than 2
220
+ * }
221
+ *
222
+ * filterExp5 = {
173
223
  * // OR condition
174
224
  * $or: [
175
225
  * { type: 'user' },
@@ -238,6 +288,7 @@ class FilterExpressionBuilder {
238
288
  "$contains",
239
289
  "$beginsWith",
240
290
  "$exists",
291
+ "$size",
241
292
  ];
242
293
  if (!validOperators.includes(op)) {
243
294
  throw new QueryError(`Invalid operator ${op} for field ${key}`);
@@ -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
  }