dynamo-bao 0.3.0 → 0.3.2
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 +220 -0
- package/package.json +1 -1
- package/src/fields.js +316 -0
- package/src/filter-expression.js +59 -8
- package/src/mixins/mutation-mixin.js +46 -10
- package/src/mixins/validation-mixin.js +26 -10
- package/src/model.js +12 -2
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
package/src/fields.js
CHANGED
|
@@ -776,6 +776,319 @@ 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
|
+
* Supports direct mutation operations that automatically track changes:
|
|
787
|
+
* - `add(value)` - Add a string to the set
|
|
788
|
+
* - `delete(value)` - Remove a string from the set
|
|
789
|
+
* - `clear()` - Remove all strings from the set
|
|
790
|
+
*
|
|
791
|
+
* @example
|
|
792
|
+
* // Creating with initial values
|
|
793
|
+
* const doc = new MyModel({
|
|
794
|
+
* tags: new Set(["javascript", "web", "tutorial"])
|
|
795
|
+
* });
|
|
796
|
+
*
|
|
797
|
+
* // Direct mutations (recommended - changes are auto-tracked)
|
|
798
|
+
* doc.tags.add("advanced"); // Add a tag
|
|
799
|
+
* doc.tags.delete("tutorial"); // Remove a tag
|
|
800
|
+
* doc.tags.clear(); // Clear all tags
|
|
801
|
+
* await doc.save(); // Changes are saved automatically
|
|
802
|
+
*
|
|
803
|
+
* // Alternative: Replace entire set
|
|
804
|
+
* doc.tags = new Set(["new", "tags"]);
|
|
805
|
+
* await doc.save();
|
|
806
|
+
*
|
|
807
|
+
* // Filter expressions
|
|
808
|
+
* const results = await MyModel.scan({
|
|
809
|
+
* filter: {
|
|
810
|
+
* tags: { $contains: "javascript" }, // Contains specific value
|
|
811
|
+
* tags: { $size: { $gt: 2 } } // Set size greater than 2
|
|
812
|
+
* }
|
|
813
|
+
* });
|
|
814
|
+
*/
|
|
815
|
+
class StringSetField extends BaoBaseField {
|
|
816
|
+
constructor(options = {}) {
|
|
817
|
+
super(options);
|
|
818
|
+
this.maxStringLength = options.maxStringLength;
|
|
819
|
+
this.maxMemberCount = options.maxMemberCount;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
validate(value) {
|
|
823
|
+
super.validate(value);
|
|
824
|
+
|
|
825
|
+
if (value === null || value === undefined) {
|
|
826
|
+
return true; // Allow null/undefined
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Accept both Set and Array, but prefer Set
|
|
830
|
+
let setToValidate;
|
|
831
|
+
if (value instanceof Set) {
|
|
832
|
+
setToValidate = value;
|
|
833
|
+
} else if (Array.isArray(value)) {
|
|
834
|
+
setToValidate = new Set(value);
|
|
835
|
+
} else {
|
|
836
|
+
throw new ValidationError(
|
|
837
|
+
"StringSetField value must be a Set or Array",
|
|
838
|
+
null,
|
|
839
|
+
value,
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// Validate member count
|
|
844
|
+
if (this.maxMemberCount && setToValidate.size > this.maxMemberCount) {
|
|
845
|
+
throw new ValidationError(
|
|
846
|
+
`StringSet exceeds maximum member count of ${this.maxMemberCount}`,
|
|
847
|
+
null,
|
|
848
|
+
value,
|
|
849
|
+
);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// Validate each string in the set
|
|
853
|
+
for (const item of setToValidate) {
|
|
854
|
+
if (typeof item !== "string") {
|
|
855
|
+
throw new ValidationError(
|
|
856
|
+
"StringSetField can only contain string values",
|
|
857
|
+
null,
|
|
858
|
+
value,
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
if (this.maxStringLength && item.length > this.maxStringLength) {
|
|
863
|
+
throw new ValidationError(
|
|
864
|
+
`String in set exceeds maximum length of ${this.maxStringLength}`,
|
|
865
|
+
null,
|
|
866
|
+
value,
|
|
867
|
+
);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
return true;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
getInitialValue() {
|
|
875
|
+
return new Set();
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
toDy(value) {
|
|
879
|
+
if (value === undefined) return undefined;
|
|
880
|
+
if (value === null) return null;
|
|
881
|
+
|
|
882
|
+
// Handle filter values (strings, numbers, objects) - pass through as-is
|
|
883
|
+
if (
|
|
884
|
+
typeof value === "string" ||
|
|
885
|
+
typeof value === "number" ||
|
|
886
|
+
(typeof value === "object" &&
|
|
887
|
+
!Array.isArray(value) &&
|
|
888
|
+
!(value instanceof Set))
|
|
889
|
+
) {
|
|
890
|
+
return value;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// Convert Set or Array to array for DynamoDB
|
|
894
|
+
let arrayValue;
|
|
895
|
+
if (value instanceof Set) {
|
|
896
|
+
arrayValue = Array.from(value);
|
|
897
|
+
} else if (Array.isArray(value)) {
|
|
898
|
+
arrayValue = [...new Set(value)]; // Remove duplicates
|
|
899
|
+
} else {
|
|
900
|
+
throw new ValidationError(
|
|
901
|
+
"StringSetField value must be a Set or Array",
|
|
902
|
+
null,
|
|
903
|
+
value,
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// Empty sets are stored as null in DynamoDB
|
|
908
|
+
if (arrayValue.length === 0) {
|
|
909
|
+
return null;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
return arrayValue;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
fromDy(value, modelInstance = null, fieldName = null) {
|
|
916
|
+
const baseSet = this._createBaseSet(value);
|
|
917
|
+
|
|
918
|
+
// If no model context, return plain Set (for non-property usage)
|
|
919
|
+
if (!modelInstance || !fieldName) {
|
|
920
|
+
return baseSet;
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// Return proxied Set that tracks changes
|
|
924
|
+
return this._createTrackedSet(baseSet, modelInstance, fieldName);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* @private
|
|
929
|
+
* @description
|
|
930
|
+
* Creates a plain Set from DynamoDB data without any tracking.
|
|
931
|
+
* @param {any} value - The value from DynamoDB (array, null, or undefined)
|
|
932
|
+
* @returns {Set} A plain Set object
|
|
933
|
+
*/
|
|
934
|
+
_createBaseSet(value) {
|
|
935
|
+
if (value === undefined || value === null) {
|
|
936
|
+
return new Set(); // Return empty Set for missing or null values
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
if (Array.isArray(value)) {
|
|
940
|
+
return new Set(value);
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
return new Set();
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* @private
|
|
948
|
+
* @description
|
|
949
|
+
* Creates a proxied Set that automatically tracks mutations and updates the model's underlying data.
|
|
950
|
+
* The proxy intercepts add(), delete(), and clear() operations to mark the field as dirty
|
|
951
|
+
* and update the model's _dyData immediately.
|
|
952
|
+
* @param {Set} baseSet - The base Set to proxy
|
|
953
|
+
* @param {BaoModel} modelInstance - The model instance that owns this field
|
|
954
|
+
* @param {string} fieldName - The name of the field in the model
|
|
955
|
+
* @returns {Proxy} A proxied Set that tracks changes
|
|
956
|
+
*/
|
|
957
|
+
_createTrackedSet(baseSet, modelInstance, fieldName) {
|
|
958
|
+
return new Proxy(baseSet, {
|
|
959
|
+
get(target, prop) {
|
|
960
|
+
const original = target[prop];
|
|
961
|
+
|
|
962
|
+
// Handle functions/methods
|
|
963
|
+
if (typeof original === "function") {
|
|
964
|
+
// For mutating methods, track changes and update underlying data
|
|
965
|
+
if (["add", "delete", "clear"].includes(prop)) {
|
|
966
|
+
return function (...args) {
|
|
967
|
+
const result = original.apply(target, args);
|
|
968
|
+
// Mark field as dirty in existing change tracking
|
|
969
|
+
modelInstance._changes.add(fieldName);
|
|
970
|
+
// Update the underlying _dyData with the mutated set
|
|
971
|
+
const field = modelInstance.constructor._getField(fieldName);
|
|
972
|
+
modelInstance._dyData[fieldName] = field.toDy(target);
|
|
973
|
+
return result;
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// For all other methods, bind them properly to maintain context
|
|
978
|
+
return original.bind(target);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// For non-function properties, return as-is
|
|
982
|
+
return original;
|
|
983
|
+
},
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
toGsi(value) {
|
|
988
|
+
throw new ValidationError(
|
|
989
|
+
"StringSetField does not support GSI conversion (sets cannot be indexed)",
|
|
990
|
+
null,
|
|
991
|
+
value,
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
getUpdateExpression(fieldName, value, originalValue) {
|
|
996
|
+
if (value === undefined) return null;
|
|
997
|
+
|
|
998
|
+
const attributeName = `#${fieldName}`;
|
|
999
|
+
const valueAttributeKey = `:${fieldName}`;
|
|
1000
|
+
|
|
1001
|
+
// Handle null case (remove entire field)
|
|
1002
|
+
if (value === null) {
|
|
1003
|
+
return {
|
|
1004
|
+
type: "REMOVE",
|
|
1005
|
+
expression: `${attributeName}`,
|
|
1006
|
+
attrNameKey: attributeName,
|
|
1007
|
+
attrValueKey: null,
|
|
1008
|
+
fieldName: fieldName,
|
|
1009
|
+
fieldValue: null,
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// Convert values to Arrays for DynamoDB (value is already in DynamoDB format from toDy)
|
|
1014
|
+
const newArray = Array.isArray(value) ? value : [value];
|
|
1015
|
+
const oldArray =
|
|
1016
|
+
originalValue && Array.isArray(originalValue) ? originalValue : [];
|
|
1017
|
+
|
|
1018
|
+
// If no original value or original was empty, use SET
|
|
1019
|
+
if (!originalValue || oldArray.length === 0) {
|
|
1020
|
+
return {
|
|
1021
|
+
type: "SET",
|
|
1022
|
+
expression: `${attributeName} = ${valueAttributeKey}`,
|
|
1023
|
+
attrNameKey: attributeName,
|
|
1024
|
+
attrValueKey: valueAttributeKey,
|
|
1025
|
+
fieldName: fieldName,
|
|
1026
|
+
fieldValue: newArray,
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// Convert to Sets for efficient comparison
|
|
1031
|
+
const newSet = new Set(newArray);
|
|
1032
|
+
const oldSet = new Set(oldArray);
|
|
1033
|
+
|
|
1034
|
+
// Find items to add and delete
|
|
1035
|
+
const toAdd = newArray.filter((item) => !oldSet.has(item));
|
|
1036
|
+
const toDelete = oldArray.filter((item) => !newSet.has(item));
|
|
1037
|
+
|
|
1038
|
+
// If no changes, return null
|
|
1039
|
+
if (toAdd.length === 0 && toDelete.length === 0) {
|
|
1040
|
+
return null;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// Handle mixed ADD and DELETE operations
|
|
1044
|
+
// For mixed operations, we use SET which replaces the entire set
|
|
1045
|
+
if (toAdd.length > 0 && toDelete.length > 0) {
|
|
1046
|
+
return {
|
|
1047
|
+
type: "SET",
|
|
1048
|
+
expression: `${attributeName} = ${valueAttributeKey}`,
|
|
1049
|
+
attrNameKey: attributeName,
|
|
1050
|
+
attrValueKey: valueAttributeKey,
|
|
1051
|
+
fieldName: fieldName,
|
|
1052
|
+
fieldValue: newArray,
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
// If only additions, use ADD
|
|
1057
|
+
if (toAdd.length > 0 && toDelete.length === 0) {
|
|
1058
|
+
return {
|
|
1059
|
+
type: "ADD",
|
|
1060
|
+
expression: `${attributeName} ${valueAttributeKey}`,
|
|
1061
|
+
attrNameKey: attributeName,
|
|
1062
|
+
attrValueKey: valueAttributeKey,
|
|
1063
|
+
fieldName: fieldName,
|
|
1064
|
+
fieldValue: toAdd,
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// If only deletions, use DELETE
|
|
1069
|
+
if (toDelete.length > 0 && toAdd.length === 0) {
|
|
1070
|
+
return {
|
|
1071
|
+
type: "DELETE",
|
|
1072
|
+
expression: `${attributeName} ${valueAttributeKey}`,
|
|
1073
|
+
attrNameKey: attributeName,
|
|
1074
|
+
attrValueKey: valueAttributeKey,
|
|
1075
|
+
fieldName: fieldName,
|
|
1076
|
+
fieldValue: toDelete,
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
// This shouldn't happen, but fallback to SET for safety
|
|
1081
|
+
return {
|
|
1082
|
+
type: "SET",
|
|
1083
|
+
expression: `${attributeName} = ${valueAttributeKey}`,
|
|
1084
|
+
attrNameKey: attributeName,
|
|
1085
|
+
attrValueKey: valueAttributeKey,
|
|
1086
|
+
fieldName: fieldName,
|
|
1087
|
+
fieldValue: newArray,
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
779
1092
|
// Factory functions for creating field instances
|
|
780
1093
|
const createStringField = (options) => new StringField(options);
|
|
781
1094
|
const createDateTimeField = (options) => new DateTimeField(options);
|
|
@@ -791,6 +1104,7 @@ const createBinaryField = (options) => new BinaryField(options);
|
|
|
791
1104
|
const createVersionField = (options) => new VersionField(options);
|
|
792
1105
|
const createBooleanField = (options) => new BooleanField(options);
|
|
793
1106
|
const createTtlField = (options) => new TtlField(options);
|
|
1107
|
+
const createStringSetField = (options) => new StringSetField(options);
|
|
794
1108
|
|
|
795
1109
|
// Export both the factory functions and the classes
|
|
796
1110
|
module.exports = {
|
|
@@ -808,6 +1122,7 @@ module.exports = {
|
|
|
808
1122
|
VersionField: createVersionField,
|
|
809
1123
|
BooleanField: createBooleanField,
|
|
810
1124
|
TtlField: createTtlField,
|
|
1125
|
+
StringSetField: createStringSetField,
|
|
811
1126
|
|
|
812
1127
|
// Classes (for instanceof checks)
|
|
813
1128
|
StringFieldClass: StringField,
|
|
@@ -823,4 +1138,5 @@ module.exports = {
|
|
|
823
1138
|
VersionFieldClass: VersionField,
|
|
824
1139
|
BooleanFieldClass: BooleanField,
|
|
825
1140
|
TtlFieldClass: TtlField,
|
|
1141
|
+
StringSetFieldClass: StringSetField,
|
|
826
1142
|
};
|
package/src/filter-expression.js
CHANGED
|
@@ -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(
|
|
51
|
+
return `${nameKey} <> ${this.generateValue(this.convertValue(value, model, fieldName))}`;
|
|
52
52
|
case "$gt":
|
|
53
|
-
return `${nameKey} > ${this.generateValue(
|
|
53
|
+
return `${nameKey} > ${this.generateValue(this.convertValue(value, model, fieldName))}`;
|
|
54
54
|
case "$gte":
|
|
55
|
-
return `${nameKey} >= ${this.generateValue(
|
|
55
|
+
return `${nameKey} >= ${this.generateValue(this.convertValue(value, model, fieldName))}`;
|
|
56
56
|
case "$lt":
|
|
57
|
-
return `${nameKey} < ${this.generateValue(
|
|
57
|
+
return `${nameKey} < ${this.generateValue(this.convertValue(value, model, fieldName))}`;
|
|
58
58
|
case "$lte":
|
|
59
|
-
return `${nameKey} <= ${this.generateValue(
|
|
59
|
+
return `${nameKey} <= ${this.generateValue(this.convertValue(value, model, fieldName))}`;
|
|
60
60
|
case "$contains":
|
|
61
|
-
return `contains(${nameKey}, ${this.generateValue(
|
|
61
|
+
return `contains(${nameKey}, ${this.generateValue(this.convertValue(value, model, fieldName))})`;
|
|
62
62
|
case "$beginsWith":
|
|
63
|
-
return `begins_with(${nameKey}, ${this.generateValue(
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
148
|
-
if (typeof this.iterable !==
|
|
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(
|
|
170
|
+
if (!this.hasOwnProperty("iterationBuckets")) {
|
|
157
171
|
this.iterationBuckets = 100; // Set default
|
|
158
172
|
} else {
|
|
159
|
-
if (
|
|
160
|
-
|
|
161
|
-
|
|
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
|
}
|
package/src/model.js
CHANGED
|
@@ -3,7 +3,11 @@
|
|
|
3
3
|
* This module contains the core functionality for models in Bao.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
const {
|
|
6
|
+
const {
|
|
7
|
+
RelatedFieldClass,
|
|
8
|
+
StringField,
|
|
9
|
+
StringSetFieldClass,
|
|
10
|
+
} = require("./fields");
|
|
7
11
|
const { ModelManager } = require("./model-manager");
|
|
8
12
|
const { defaultLogger: logger } = require("./utils/logger");
|
|
9
13
|
const { ObjectNotFound } = require("./object-not-found");
|
|
@@ -363,7 +367,13 @@ class BaoModel {
|
|
|
363
367
|
|
|
364
368
|
// Define property getter/setter that always works with _dyData
|
|
365
369
|
Object.defineProperty(this, fieldName, {
|
|
366
|
-
get: () =>
|
|
370
|
+
get: () => {
|
|
371
|
+
// For StringSetField, pass model context to enable proxy
|
|
372
|
+
if (field instanceof StringSetFieldClass) {
|
|
373
|
+
return field.fromDy(this._dyData[fieldName], this, fieldName);
|
|
374
|
+
}
|
|
375
|
+
return field.fromDy(this._dyData[fieldName]);
|
|
376
|
+
},
|
|
367
377
|
set: (newValue) => {
|
|
368
378
|
const oldDyValue = this._dyData[fieldName];
|
|
369
379
|
const newDyValue = field.toDy(newValue);
|