dynamo-bao 0.1.0

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.
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Supporting class for building DynamoDB filter expressions.
3
+ * @class
4
+ */
5
+ class FilterExpressionBuilder {
6
+ /**
7
+ * @constructor
8
+ * @description
9
+ * Do not instantiate this class directly. This is used by {@link BaoModel.queryByIndex}.
10
+ */
11
+ constructor() {
12
+ this.names = {};
13
+ this.values = {};
14
+ this.nameCount = 0;
15
+ this.valueCount = 0;
16
+ }
17
+
18
+ // Generate unique name placeholder
19
+ generateName(fieldName) {
20
+ const key = `#n${++this.nameCount}`;
21
+ this.names[key] = fieldName;
22
+ return key;
23
+ }
24
+
25
+ // Generate unique value placeholder
26
+ generateValue(value) {
27
+ const key = `:v${++this.valueCount}`;
28
+ this.values[key] = value;
29
+ return key;
30
+ }
31
+
32
+ // Simplified value conversion - let the field handle it
33
+ convertValue(value, model, fieldName) {
34
+ const field = model.fields[fieldName];
35
+ return field.toDy(value);
36
+ }
37
+
38
+ // Build expression for a single comparison
39
+ buildComparison(fieldName, operator, value, model) {
40
+ const nameKey = this.generateName(fieldName);
41
+ const convertedValue = this.convertValue(value, model, fieldName);
42
+
43
+ switch (operator) {
44
+ case "$eq":
45
+ const valueKey = this.generateValue(convertedValue);
46
+ return `${nameKey} = ${valueKey}`;
47
+ case "$ne":
48
+ return `${nameKey} <> ${this.generateValue(convertedValue)}`;
49
+ case "$gt":
50
+ return `${nameKey} > ${this.generateValue(convertedValue)}`;
51
+ case "$gte":
52
+ return `${nameKey} >= ${this.generateValue(convertedValue)}`;
53
+ case "$lt":
54
+ return `${nameKey} < ${this.generateValue(convertedValue)}`;
55
+ case "$lte":
56
+ return `${nameKey} <= ${this.generateValue(convertedValue)}`;
57
+ case "$contains":
58
+ return `contains(${nameKey}, ${this.generateValue(convertedValue)})`;
59
+ case "$beginsWith":
60
+ return `begins_with(${nameKey}, ${this.generateValue(convertedValue)})`;
61
+ case "$in":
62
+ if (!Array.isArray(convertedValue)) {
63
+ throw new Error("$in operator requires an array value");
64
+ }
65
+ const valueKeys = convertedValue.map((v) => this.generateValue(v));
66
+ return `${nameKey} IN (${valueKeys.join(", ")})`;
67
+ default:
68
+ throw new Error(`Unsupported operator: ${operator}`);
69
+ }
70
+ }
71
+
72
+ // Build expression for a field
73
+ buildFieldExpression(fieldName, condition, model) {
74
+ if (condition === null) {
75
+ const nameKey = this.generateName(fieldName);
76
+ return `attribute_not_exists(${nameKey})`;
77
+ }
78
+
79
+ if (typeof condition !== "object" || condition instanceof Date) {
80
+ return this.buildComparison(fieldName, "$eq", condition, model);
81
+ }
82
+
83
+ const operators = Object.keys(condition);
84
+ if (operators.length === 0) {
85
+ throw new Error(`Empty condition object for field: ${fieldName}`);
86
+ }
87
+
88
+ const expressions = operators.map((operator) => {
89
+ return this.buildComparison(
90
+ fieldName,
91
+ operator,
92
+ condition[operator],
93
+ model,
94
+ );
95
+ });
96
+
97
+ return expressions.join(" AND ");
98
+ }
99
+
100
+ // Build expression for logical operators
101
+ buildLogicalExpression(operator, conditions, model) {
102
+ if (!Array.isArray(conditions)) {
103
+ throw new Error(`${operator} requires an array of conditions`);
104
+ }
105
+
106
+ const expressions = conditions.map((condition) => {
107
+ return this.buildFilterExpression(condition, model);
108
+ });
109
+
110
+ const joinOperator = operator === "$and" ? " AND " : " OR ";
111
+ return `(${expressions.join(joinOperator)})`;
112
+ }
113
+
114
+ // Main entry point for building filter expression
115
+ buildFilterExpression(filter, model) {
116
+ if (!filter || Object.keys(filter).length === 0) {
117
+ return null;
118
+ }
119
+
120
+ const expressions = [];
121
+
122
+ for (const [key, value] of Object.entries(filter)) {
123
+ if (key === "$and" || key === "$or") {
124
+ expressions.push(this.buildLogicalExpression(key, value, model));
125
+ } else if (key === "$not") {
126
+ const innerExpr = this.buildFilterExpression(value, model);
127
+ expressions.push(`NOT ${innerExpr}`);
128
+ } else {
129
+ expressions.push(this.buildFieldExpression(key, value, model));
130
+ }
131
+ }
132
+
133
+ return expressions.join(" AND ");
134
+ }
135
+
136
+ /**
137
+ * Build a filter expression for a given filter and model.
138
+ * @param {Object} filter - The filter object to build the expression for. The filter can contain:
139
+ * - Simple field comparisons: { fieldName: value } for exact matches
140
+ * - Comparison operators: { fieldName: { $eq: value, $ne: value, $gt: value, $gte: value, $lt: value, $lte: value } }
141
+ * - String operators: { fieldName: { $beginsWith: value, $contains: value } }
142
+ * - Logical operators:
143
+ * - $and: [{condition1}, {condition2}] - All conditions must match
144
+ * - $or: [{condition1}, {condition2}] - At least one condition must match
145
+ * - $not: {condition} - Condition must not match
146
+ * @param {BaoModel} model - The model to build the expression for. Used to validate field names.
147
+ * @example
148
+ * filterExp1 = {
149
+ * status: 'active', // Exact match
150
+ * }
151
+ *
152
+ * filterExp2 = {
153
+ * age: { $gt: 21 }, // Greater than comparison
154
+ * }
155
+ *
156
+ * filterExp3 = {
157
+ * roles: { $contains: 'admin' }, // String contains
158
+ * }
159
+ *
160
+ * filterExp4 = {
161
+ * // OR condition
162
+ * $or: [
163
+ * { type: 'user' },
164
+ * { type: 'admin' }
165
+ * ]
166
+ * }
167
+ * @returns {Object|null} Returns null if no filter provided, otherwise returns an object containing:
168
+ * - FilterExpression: String DynamoDB filter expression
169
+ * - ExpressionAttributeNames: Map of attribute name placeholders
170
+ * - ExpressionAttributeValues: Map of attribute value placeholders
171
+ */
172
+ build(filter, model) {
173
+ // Validate field names against model
174
+ this.validateFields(filter, model);
175
+
176
+ const filterExpression = this.buildFilterExpression(filter, model);
177
+
178
+ if (!filterExpression) {
179
+ return null;
180
+ }
181
+
182
+ return {
183
+ FilterExpression: filterExpression,
184
+ ExpressionAttributeNames: this.names,
185
+ ExpressionAttributeValues: this.values,
186
+ };
187
+ }
188
+
189
+ // Validate fields against model definition
190
+ validateFields(filter, model) {
191
+ const validateObject = (obj) => {
192
+ for (const [key, value] of Object.entries(obj)) {
193
+ // Skip logical operators
194
+ if (["$and", "$or", "$not"].includes(key)) {
195
+ if (Array.isArray(value)) {
196
+ value.forEach(validateObject);
197
+ } else {
198
+ validateObject(value);
199
+ }
200
+ continue;
201
+ }
202
+
203
+ // Validate field exists in model
204
+ if (!model.fields[key]) {
205
+ throw new Error(`Unknown field in filter: ${key}`);
206
+ }
207
+
208
+ // Recursively validate nested conditions
209
+ if (
210
+ value &&
211
+ typeof value === "object" &&
212
+ !Array.isArray(value) &&
213
+ !(value instanceof Date)
214
+ ) {
215
+ const operators = Object.keys(value);
216
+ operators.forEach((op) => {
217
+ if (
218
+ ![
219
+ "$eq",
220
+ "$ne",
221
+ "$gt",
222
+ "$gte",
223
+ "$lt",
224
+ "$lte",
225
+ "$in",
226
+ "$contains",
227
+ "$beginsWith",
228
+ ].includes(op)
229
+ ) {
230
+ throw new Error(`Invalid operator ${op} for field ${key}`);
231
+ }
232
+ });
233
+ }
234
+ }
235
+ };
236
+
237
+ validateObject(filter);
238
+ }
239
+ }
240
+
241
+ module.exports = { FilterExpressionBuilder };
package/src/index.js ADDED
@@ -0,0 +1,127 @@
1
+ // src/index.js
2
+ const config = require("./config");
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { ModelManager } = require("./model-manager");
6
+ const { defaultLogger: logger } = require("./utils/logger");
7
+ const fields = require("./fields");
8
+ const constants = require("./constants");
9
+
10
+ const {
11
+ BaoModel,
12
+ PrimaryKeyConfig,
13
+ IndexConfig,
14
+ UniqueConstraintConfig,
15
+ } = require("./model");
16
+
17
+ function findModelFiles(dir) {
18
+ let results = [];
19
+ const items = fs.readdirSync(dir);
20
+
21
+ items.forEach((item) => {
22
+ const fullPath = path.join(dir, item);
23
+ const stat = fs.statSync(fullPath);
24
+
25
+ if (stat.isDirectory()) {
26
+ // Recursively search subdirectories
27
+ results = results.concat(findModelFiles(fullPath));
28
+ } else if (item.endsWith(".js")) {
29
+ results.push(fullPath);
30
+ }
31
+ });
32
+
33
+ return results;
34
+ }
35
+
36
+ function _registerModels(manager = null, modelsDir = null) {
37
+ if (!modelsDir) {
38
+ throw new Error("modelsDir is required");
39
+ return;
40
+ }
41
+
42
+ const modelFiles = findModelFiles(modelsDir);
43
+ const models = {};
44
+
45
+ modelFiles.forEach((file) => {
46
+ const model = require(file);
47
+ Object.entries(model).forEach(([name, ModelClass]) => {
48
+ manager.registerModel(ModelClass);
49
+ models[name] = ModelClass;
50
+ });
51
+ });
52
+
53
+ return models;
54
+ }
55
+
56
+ function initModels(userConfig = {}) {
57
+ // Merge user config with default config
58
+ const finalConfig = {
59
+ ...config,
60
+ ...userConfig,
61
+ // Preserve nested configs if provided
62
+ aws: {
63
+ ...config.aws,
64
+ ...(userConfig.aws || {}),
65
+ },
66
+ db: {
67
+ ...config.db,
68
+ ...(userConfig.db || {}),
69
+ },
70
+ logging: {
71
+ ...config.logging,
72
+ ...(userConfig.logging || {}),
73
+ },
74
+ paths: {
75
+ ...config.paths,
76
+ ...(userConfig.paths || {}),
77
+ },
78
+ };
79
+
80
+ const modelsDir = finalConfig.paths.modelsDir;
81
+
82
+ // Get/create manager instance with testId
83
+ const manager = ModelManager.getInstance(finalConfig.testId);
84
+
85
+ // First pass to register models
86
+ const registeredModels = _registerModels(manager, modelsDir);
87
+
88
+ // Initialize the manager & 2nd model registration pass
89
+ manager.init(finalConfig);
90
+
91
+ logger.log("Models initialized:", {
92
+ testId: finalConfig.testId,
93
+ managerTestId: manager.getTestId(),
94
+ registeredModels: Array.from(manager._models.keys()),
95
+ });
96
+
97
+ manager.models = registeredModels;
98
+
99
+ return manager;
100
+ }
101
+
102
+ const firstExport = {
103
+ // Initialize function
104
+ initModels,
105
+
106
+ // Core classes
107
+ BaoModel,
108
+ ModelManager,
109
+ fields,
110
+
111
+ // Configurations
112
+ PrimaryKeyConfig,
113
+ IndexConfig,
114
+ UniqueConstraintConfig,
115
+
116
+ // Export the constants module directly
117
+ constants,
118
+
119
+ models: {},
120
+ };
121
+
122
+ module.exports = firstExport;
123
+
124
+ if (config.paths.modelsDir) {
125
+ const manager = initModels(config);
126
+ Object.assign(firstExport.models, manager.models);
127
+ }
@@ -0,0 +1,258 @@
1
+ class KeyConditionBuilder {
2
+ constructor() {
3
+ this.names = {};
4
+ this.values = {};
5
+ this.nameCount = 0;
6
+ this.valueCount = 0;
7
+
8
+ // Define operator mappings
9
+ this.operatorMap = {
10
+ $gt: ">",
11
+ $gte: ">=",
12
+ $lt: "<",
13
+ $lte: "<=",
14
+ };
15
+ }
16
+
17
+ generateName(fieldName) {
18
+ const key = `#n${++this.nameCount}`;
19
+ this.names[key] = fieldName;
20
+ return key;
21
+ }
22
+
23
+ generateValue(value) {
24
+ const key = `:v${++this.valueCount}`;
25
+ this.values[key] = value;
26
+ return key;
27
+ }
28
+
29
+ validateSortKeyField(model, indexName, fieldName) {
30
+ const index = model.indexes[indexName];
31
+ if (!index) {
32
+ throw new Error(`Index "${indexName}" not found in ${model.name}`);
33
+ }
34
+
35
+ if (index.sk === "modelPrefix") {
36
+ throw new Error(
37
+ `Cannot query by sort key on index "${indexName}" as it uses modelPrefix`,
38
+ );
39
+ }
40
+
41
+ const skField = index.sk;
42
+ if (skField !== fieldName) {
43
+ throw new Error(
44
+ `Field "${fieldName}" is not the sort key for index "${indexName}". ` +
45
+ `Expected "${skField}"`,
46
+ );
47
+ }
48
+ }
49
+
50
+ buildSortKeyExpression(skField, condition) {
51
+ if (condition === null || condition === undefined) {
52
+ return null;
53
+ }
54
+
55
+ const nameKey = this.generateName(skField);
56
+
57
+ // Handle simple value case (treated as equality)
58
+ if (typeof condition !== "object") {
59
+ const valueKey = this.generateValue(condition);
60
+ return {
61
+ condition: `${nameKey} = ${valueKey}`,
62
+ names: this.names,
63
+ values: this.values,
64
+ };
65
+ }
66
+
67
+ // Handle operator object
68
+ const operator = Object.keys(condition)[0];
69
+ const value = condition[operator];
70
+
71
+ switch (operator) {
72
+ case "$eq":
73
+ const valueKey = this.generateValue(value);
74
+ return {
75
+ condition: `${nameKey} = ${valueKey}`,
76
+ names: this.names,
77
+ values: this.values,
78
+ };
79
+
80
+ case "$beginsWith":
81
+ return {
82
+ condition: `begins_with(${nameKey}, ${this.generateValue(value)})`,
83
+ names: this.names,
84
+ values: this.values,
85
+ };
86
+
87
+ case "$between":
88
+ if (!Array.isArray(value) || value.length !== 2) {
89
+ throw new Error("$between requires an array with exactly 2 elements");
90
+ }
91
+ return {
92
+ condition: `${nameKey} BETWEEN ${this.generateValue(value[0])} AND ${this.generateValue(value[1])}`,
93
+ names: this.names,
94
+ values: this.values,
95
+ };
96
+
97
+ case "$gt":
98
+ case "$gte":
99
+ case "$lt":
100
+ case "$lte":
101
+ const operators = {
102
+ $gt: ">",
103
+ $gte: ">=",
104
+ $lt: "<",
105
+ $lte: "<=",
106
+ };
107
+ return {
108
+ condition: `${nameKey} ${operators[operator]} ${this.generateValue(value)}`,
109
+ names: this.names,
110
+ values: this.values,
111
+ };
112
+
113
+ default:
114
+ throw new Error(`Unsupported sort key operator: ${operator}`);
115
+ }
116
+ }
117
+
118
+ buildBetweenCondition(fieldName, values) {
119
+ return {
120
+ condition: `#${fieldName} BETWEEN :${fieldName}_start AND :${fieldName}_end`,
121
+ names: {
122
+ [`#${fieldName}`]: fieldName,
123
+ },
124
+ values: {
125
+ [`:${fieldName}_start`]: values[0],
126
+ [`:${fieldName}_end`]: values[1],
127
+ },
128
+ };
129
+ }
130
+
131
+ buildSimpleCondition(fieldName, value) {
132
+ const nameKey = this.generateName(fieldName);
133
+ const valueKey = this.generateValue(value);
134
+ return {
135
+ condition: `${nameKey} = ${valueKey}`,
136
+ names: this.names,
137
+ values: this.values,
138
+ };
139
+ }
140
+
141
+ buildBeginsWithCondition(fieldName, value) {
142
+ const nameKey = this.generateName(fieldName);
143
+ const valueKey = this.generateValue(value);
144
+ return {
145
+ condition: `begins_with(${nameKey}, ${valueKey})`,
146
+ names: this.names,
147
+ values: this.values,
148
+ };
149
+ }
150
+
151
+ buildComparisonCondition(fieldName, operator, value) {
152
+ const nameKey = this.generateName(fieldName);
153
+ const valueKey = this.generateValue(value);
154
+ const operators = {
155
+ $gt: ">",
156
+ $gte: ">=",
157
+ $lt: "<",
158
+ $lte: "<=",
159
+ };
160
+ return {
161
+ condition: `${nameKey} ${operators[operator]} ${valueKey}`,
162
+ names: this.names,
163
+ values: this.values,
164
+ };
165
+ }
166
+
167
+ buildKeyCondition(model, indexName, condition, gsiSortKeyName) {
168
+ // Validate the condition format
169
+ if (!condition || typeof condition !== "object") {
170
+ throw new Error("Invalid condition format");
171
+ }
172
+
173
+ const [[fieldName, fieldCondition]] = Object.entries(condition);
174
+
175
+ // Validate that this field is the sort key for the index
176
+ const index = model.indexes[indexName];
177
+ if (!index || index.sk !== fieldName) {
178
+ throw new Error(
179
+ `Field "${fieldName}" is not the sort key for index "${indexName}"`,
180
+ );
181
+ }
182
+
183
+ // Get the field definition to use its toGsi method
184
+ const field = model._getField(fieldName);
185
+ const nameKey = "#sk";
186
+ const names = { "#sk": gsiSortKeyName };
187
+
188
+ // Handle operator object
189
+ if (typeof fieldCondition === "object" && fieldCondition !== null) {
190
+ const operator = Object.keys(fieldCondition)[0];
191
+ const value = fieldCondition[operator];
192
+
193
+ // Validate operator before processing
194
+ const validOperators = [
195
+ "$eq",
196
+ "$beginsWith",
197
+ "$between",
198
+ "$gt",
199
+ "$gte",
200
+ "$lt",
201
+ "$lte",
202
+ ];
203
+ if (!validOperators.includes(operator)) {
204
+ throw new Error(`Unsupported sort key operator: ${operator}`);
205
+ }
206
+
207
+ switch (operator) {
208
+ case "$between":
209
+ if (!Array.isArray(value) || value.length !== 2) {
210
+ throw new Error(
211
+ "$between requires an array with exactly 2 elements",
212
+ );
213
+ }
214
+ return {
215
+ condition: `${nameKey} BETWEEN :sortKeyStart AND :sortKeyEnd`,
216
+ names,
217
+ values: {
218
+ ":sortKeyStart": field.toGsi(value[0]),
219
+ ":sortKeyEnd": field.toGsi(value[1]),
220
+ },
221
+ };
222
+
223
+ case "$gt":
224
+ case "$gte":
225
+ case "$lt":
226
+ case "$lte":
227
+ return {
228
+ condition: `${nameKey} ${this.operatorMap[operator]} :sortKeyValue`,
229
+ names,
230
+ values: { ":sortKeyValue": field.toGsi(value) },
231
+ };
232
+
233
+ case "$beginsWith":
234
+ return {
235
+ condition: `begins_with(${nameKey}, :sortKeyValue)`,
236
+ names,
237
+ values: { ":sortKeyValue": field.toGsi(value) },
238
+ };
239
+
240
+ default:
241
+ throw new Error(`Unsupported sort key operator: ${operator}`);
242
+ }
243
+ }
244
+
245
+ // Handle simple value case (treated as equality)
246
+ if (fieldCondition === undefined) {
247
+ throw new Error("Sort key condition value cannot be undefined");
248
+ }
249
+
250
+ return {
251
+ condition: `${nameKey} = :sortKeyValue`,
252
+ names,
253
+ values: { ":sortKeyValue": field.toGsi(fieldCondition) },
254
+ };
255
+ }
256
+ }
257
+
258
+ module.exports = { KeyConditionBuilder };