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.
- package/README.md +322 -2
- package/package.json +1 -1
- package/src/config.js +23 -11
- package/src/fields.js +227 -0
- package/src/filter-expression.js +59 -8
- package/src/index.js +4 -0
- package/src/mixins/batch-loading-mixin.js +107 -42
- package/src/mixins/mutation-mixin.js +46 -10
- package/src/mixins/validation-mixin.js +26 -10
- package/src/model-manager.js +8 -2
- package/src/model.js +13 -25
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
|
};
|
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}`);
|
package/src/index.js
CHANGED
|
@@ -165,6 +165,10 @@ function initModels(userConfig = {}) {
|
|
|
165
165
|
...config.tenancy,
|
|
166
166
|
...(userConfig.tenancy || {}),
|
|
167
167
|
},
|
|
168
|
+
batchContext: {
|
|
169
|
+
...config.batchContext,
|
|
170
|
+
...(userConfig.batchContext || {}),
|
|
171
|
+
},
|
|
168
172
|
models: userConfig.models || config.models || null,
|
|
169
173
|
};
|
|
170
174
|
|
|
@@ -2,6 +2,7 @@ const { defaultLogger: logger } = require("../utils/logger");
|
|
|
2
2
|
const { ObjectNotFound } = require("../object-not-found");
|
|
3
3
|
const { pluginManager } = require("../plugin-manager");
|
|
4
4
|
const { BatchGetCommand, GetCommand } = require("../dynamodb-client");
|
|
5
|
+
const defaultConfig = require("../config");
|
|
5
6
|
|
|
6
7
|
// Import AsyncLocalStorage for request-scoped batching
|
|
7
8
|
let AsyncLocalStorage;
|
|
@@ -15,15 +16,12 @@ try {
|
|
|
15
16
|
// Request-scoped batch context
|
|
16
17
|
const batchContext = AsyncLocalStorage ? new AsyncLocalStorage() : null;
|
|
17
18
|
|
|
18
|
-
// Fallback global state for environments without AsyncLocalStorage (primarily for testing)
|
|
19
|
-
const FALLBACK_BATCH_REQUESTS = new Map(); // testId -> { modelName-delay -> batch }
|
|
20
|
-
|
|
21
19
|
const DEFAULT_BATCH_DELAY_MS = 5;
|
|
22
20
|
const BATCH_REQUEST_TIMEOUT = 10000; // 10 seconds max lifetime for a batch
|
|
23
21
|
|
|
24
22
|
const BatchLoadingMethods = {
|
|
25
23
|
_getBatchRequests() {
|
|
26
|
-
//
|
|
24
|
+
// AsyncLocalStorage is required - check for context
|
|
27
25
|
if (batchContext) {
|
|
28
26
|
const context = batchContext.getStore();
|
|
29
27
|
if (context && context.batchRequests) {
|
|
@@ -31,25 +29,34 @@ const BatchLoadingMethods = {
|
|
|
31
29
|
}
|
|
32
30
|
}
|
|
33
31
|
|
|
34
|
-
//
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
32
|
+
// Check if we should require batch context
|
|
33
|
+
const modelConfig = this._config || {};
|
|
34
|
+
const batchContextConfig = modelConfig.batchContext || {
|
|
35
|
+
requireBatchContext: false,
|
|
36
|
+
};
|
|
37
|
+
if (batchContextConfig.requireBatchContext) {
|
|
38
|
+
// No batch context found - operations must be within runWithBatchContext
|
|
39
|
+
throw new Error(
|
|
40
|
+
"Batch operations must be executed within runWithBatchContext(). " +
|
|
41
|
+
"Wrap your database operations in runWithBatchContext() to enable batching and caching.",
|
|
42
|
+
);
|
|
42
43
|
}
|
|
43
44
|
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"No batch context found. Batching is disabled for safety. " +
|
|
48
|
-
"Use runWithBatchContext() in Cloudflare Workers for optimal performance.",
|
|
49
|
-
);
|
|
45
|
+
// Fallback: Return null to indicate no batch context available
|
|
46
|
+
return null;
|
|
47
|
+
},
|
|
50
48
|
|
|
51
|
-
|
|
52
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Check if currently executing within a batch context
|
|
51
|
+
* @returns {boolean} True if inside a batch context, false otherwise
|
|
52
|
+
*/
|
|
53
|
+
isInsideBatchContext() {
|
|
54
|
+
if (!batchContext) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const context = batchContext.getStore();
|
|
59
|
+
return !!(context && context.batchRequests);
|
|
53
60
|
},
|
|
54
61
|
|
|
55
62
|
/**
|
|
@@ -59,12 +66,16 @@ const BatchLoadingMethods = {
|
|
|
59
66
|
* This function should only be used when {@link BaoModel.find} or {@link BaoModel#loadRelatedData} is not sufficient.
|
|
60
67
|
*
|
|
61
68
|
* @param {string[]} primaryIds - The primary IDs of the items to load
|
|
62
|
-
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
63
69
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
64
70
|
*/
|
|
65
|
-
async batchFind(primaryIds
|
|
71
|
+
async batchFind(primaryIds) {
|
|
66
72
|
if (!primaryIds?.length) return { items: {}, ConsumedCapacity: [] };
|
|
67
73
|
|
|
74
|
+
// Get batch context and loader context - will be null if not in batch context
|
|
75
|
+
const batchRequests = this._getBatchRequests();
|
|
76
|
+
const context = batchContext?.getStore();
|
|
77
|
+
const loaderContext = context?.loaderContext;
|
|
78
|
+
|
|
68
79
|
// Add retry wrapper function
|
|
69
80
|
const retryOperation = async (operation, maxRetries = 3) => {
|
|
70
81
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
@@ -96,8 +107,10 @@ const BatchLoadingMethods = {
|
|
|
96
107
|
// First check loaderContext for existing items
|
|
97
108
|
if (loaderContext) {
|
|
98
109
|
primaryIds.forEach((id) => {
|
|
99
|
-
if (loaderContext
|
|
100
|
-
const instance = this._createFromDyItem(
|
|
110
|
+
if (loaderContext.has(id)) {
|
|
111
|
+
const instance = this._createFromDyItem(
|
|
112
|
+
loaderContext.get(id)._dyData,
|
|
113
|
+
);
|
|
101
114
|
results[id] = instance;
|
|
102
115
|
} else {
|
|
103
116
|
idsToLoad.push(id);
|
|
@@ -153,7 +166,7 @@ const BatchLoadingMethods = {
|
|
|
153
166
|
|
|
154
167
|
// Add to loader context if provided
|
|
155
168
|
if (loaderContext) {
|
|
156
|
-
loaderContext
|
|
169
|
+
loaderContext.set(primaryId, instance);
|
|
157
170
|
}
|
|
158
171
|
});
|
|
159
172
|
}
|
|
@@ -203,23 +216,50 @@ const BatchLoadingMethods = {
|
|
|
203
216
|
* @param {Object} [options={}] - Optional configuration for the find operation
|
|
204
217
|
* @param {number} [options.batchDelay=5] - Delay in milliseconds before executing batch request.
|
|
205
218
|
* Set to 0 for immediate individual requests
|
|
206
|
-
* @param {
|
|
207
|
-
* If provided, results will be stored in and retrieved from this context
|
|
219
|
+
* @param {boolean} [options.bypassCache=false] - If true, bypasses both batching and caching entirely
|
|
208
220
|
* @returns {Promise<Object>} Returns a promise that resolves to the found item instance or ObjectNotFound
|
|
209
221
|
* @throws {Error} If the batch request times out or other errors occur during the operation
|
|
210
222
|
*/
|
|
211
223
|
async find(primaryId, options = {}) {
|
|
212
224
|
const batchDelay = options.batchDelay ?? DEFAULT_BATCH_DELAY_MS;
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
//
|
|
216
|
-
if (
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
225
|
+
const bypassCache = options.bypassCache ?? false;
|
|
226
|
+
|
|
227
|
+
// Ensure we're within a batch context (unless bypassing everything for AsyncLocalStorage availability check)
|
|
228
|
+
if (!batchContext) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
"AsyncLocalStorage is not available. Dynamo-bao requires Node.js with AsyncLocalStorage support.",
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const context = batchContext.getStore();
|
|
235
|
+
if (!context) {
|
|
236
|
+
// Check if we should require batch context
|
|
237
|
+
const modelConfig = this._config || {};
|
|
238
|
+
const batchContextConfig = modelConfig.batchContext || {
|
|
239
|
+
requireBatchContext: false,
|
|
240
|
+
};
|
|
241
|
+
if (batchContextConfig.requireBatchContext) {
|
|
242
|
+
throw new Error(
|
|
243
|
+
"Batch operations must be executed within runWithBatchContext(). " +
|
|
244
|
+
"Wrap your database operations in runWithBatchContext() to enable batching and caching.",
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Fallback behavior: direct execution without batching or caching
|
|
249
|
+
return this._executeFindDirect(primaryId);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Get automatic loaderContext from batch context
|
|
253
|
+
let loaderContext = null;
|
|
254
|
+
if (!bypassCache && context?.loaderContext) {
|
|
255
|
+
loaderContext = context.loaderContext;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Check loader context first (unless bypassing cache)
|
|
259
|
+
if (!bypassCache && loaderContext && loaderContext.has(primaryId)) {
|
|
260
|
+
const cachedItem = loaderContext.get(primaryId);
|
|
261
|
+
// Return the exact same cached object instance for true caching
|
|
262
|
+
return cachedItem;
|
|
223
263
|
}
|
|
224
264
|
|
|
225
265
|
if (batchDelay === 0) {
|
|
@@ -242,9 +282,9 @@ const BatchLoadingMethods = {
|
|
|
242
282
|
instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
|
|
243
283
|
}
|
|
244
284
|
|
|
245
|
-
// Add to loader context if provided
|
|
246
|
-
if (loaderContext) {
|
|
247
|
-
loaderContext
|
|
285
|
+
// Add to loader context if provided (unless bypassing cache)
|
|
286
|
+
if (!bypassCache && loaderContext) {
|
|
287
|
+
loaderContext.set(primaryId, instance);
|
|
248
288
|
}
|
|
249
289
|
|
|
250
290
|
return instance;
|
|
@@ -264,7 +304,7 @@ const BatchLoadingMethods = {
|
|
|
264
304
|
timeoutTimer: null,
|
|
265
305
|
delay: batchDelay,
|
|
266
306
|
createdAt: Date.now(),
|
|
267
|
-
loaderContext,
|
|
307
|
+
loaderContext: bypassCache ? null : loaderContext,
|
|
268
308
|
};
|
|
269
309
|
batchRequests.set(batchKey, batchRequest);
|
|
270
310
|
|
|
@@ -361,6 +401,31 @@ const BatchLoadingMethods = {
|
|
|
361
401
|
}
|
|
362
402
|
});
|
|
363
403
|
},
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Execute find operation directly without batching or caching
|
|
407
|
+
* @param {string} primaryId - The primary ID to find
|
|
408
|
+
* @returns {Promise<Object>} The found item or ObjectNotFound
|
|
409
|
+
*/
|
|
410
|
+
async _executeFindDirect(primaryId) {
|
|
411
|
+
const pkSk = this._parsePrimaryId(primaryId);
|
|
412
|
+
const dyKey = this._getDyKeyForPkSk(pkSk);
|
|
413
|
+
const result = await this.documentClient.send(
|
|
414
|
+
new GetCommand({
|
|
415
|
+
TableName: this.table,
|
|
416
|
+
Key: dyKey,
|
|
417
|
+
ReturnConsumedCapacity: "TOTAL",
|
|
418
|
+
}),
|
|
419
|
+
);
|
|
420
|
+
|
|
421
|
+
if (!result.Item) {
|
|
422
|
+
return new ObjectNotFound(result.ConsumedCapacity);
|
|
423
|
+
} else {
|
|
424
|
+
const instance = this._createFromDyItem(result.Item);
|
|
425
|
+
instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
|
|
426
|
+
return instance;
|
|
427
|
+
}
|
|
428
|
+
},
|
|
364
429
|
};
|
|
365
430
|
|
|
366
431
|
/**
|
|
@@ -378,6 +443,7 @@ function runWithBatchContext(fn) {
|
|
|
378
443
|
const context = {
|
|
379
444
|
requestId: Date.now().toString(36) + Math.random().toString(36).substr(2),
|
|
380
445
|
batchRequests: new Map(),
|
|
446
|
+
loaderContext: new Map(), // Add automatic loaderContext
|
|
381
447
|
timers: new Set(),
|
|
382
448
|
startTime: Date.now(),
|
|
383
449
|
};
|
|
@@ -388,7 +454,6 @@ function runWithBatchContext(fn) {
|
|
|
388
454
|
module.exports = {
|
|
389
455
|
BatchLoadingMethods,
|
|
390
456
|
runWithBatchContext,
|
|
391
|
-
FALLBACK_BATCH_REQUESTS,
|
|
392
457
|
DEFAULT_BATCH_DELAY_MS,
|
|
393
458
|
BATCH_REQUEST_TIMEOUT,
|
|
394
459
|
};
|