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/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
|
|
|
@@ -181,9 +182,109 @@ export default {
|
|
|
181
182
|
**Request Isolation**:
|
|
182
183
|
|
|
183
184
|
- **With `runWithBatchContext`**: Each request gets its own isolated batch context with optimal batching performance
|
|
184
|
-
- **Without `runWithBatchContext`**:
|
|
185
|
+
- **Without `runWithBatchContext`**: Operations automatically fall back to direct execution (no batching/caching) to ensure request isolation
|
|
185
186
|
|
|
186
|
-
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and performance.
|
|
187
|
+
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and optimal performance.
|
|
188
|
+
|
|
189
|
+
### Batch Context Configuration
|
|
190
|
+
|
|
191
|
+
DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
|
|
192
|
+
|
|
193
|
+
#### Configuration Options
|
|
194
|
+
|
|
195
|
+
Add the `batchContext` configuration to your config file:
|
|
196
|
+
|
|
197
|
+
```javascript
|
|
198
|
+
// config.js or dynamo-bao.config.js
|
|
199
|
+
module.exports = {
|
|
200
|
+
aws: {
|
|
201
|
+
region: "us-west-2",
|
|
202
|
+
},
|
|
203
|
+
db: {
|
|
204
|
+
tableName: "your-table-name",
|
|
205
|
+
},
|
|
206
|
+
batchContext: {
|
|
207
|
+
requireBatchContext: false, // Default: allow fallback behavior
|
|
208
|
+
},
|
|
209
|
+
// ... other config
|
|
210
|
+
};
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
#### Behavior Modes
|
|
214
|
+
|
|
215
|
+
**Default Mode (`requireBatchContext: false`)**:
|
|
216
|
+
|
|
217
|
+
- Operations inside `runWithBatchContext`: Full batching and caching enabled
|
|
218
|
+
- Operations outside `runWithBatchContext`: Direct execution without batching or caching
|
|
219
|
+
- Provides maximum flexibility and backward compatibility
|
|
220
|
+
|
|
221
|
+
```javascript
|
|
222
|
+
// Works with direct execution (no batching/caching)
|
|
223
|
+
const user = await User.find("user123");
|
|
224
|
+
|
|
225
|
+
// Also works with batching + caching
|
|
226
|
+
await runWithBatchContext(async () => {
|
|
227
|
+
const user = await User.find("user123");
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
**Strict Mode (`requireBatchContext: true`)**:
|
|
232
|
+
|
|
233
|
+
- Operations inside `runWithBatchContext`: Full batching and caching enabled
|
|
234
|
+
- Operations outside `runWithBatchContext`: Throws an error
|
|
235
|
+
- Ensures all database operations use proper batch context
|
|
236
|
+
|
|
237
|
+
```javascript
|
|
238
|
+
// Configure strict mode
|
|
239
|
+
const manager = initModels({
|
|
240
|
+
batchContext: { requireBatchContext: true },
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// This throws an error
|
|
244
|
+
await User.find("user123"); // Error: Batch operations must be executed within runWithBatchContext()
|
|
245
|
+
|
|
246
|
+
// This works
|
|
247
|
+
await runWithBatchContext(async () => {
|
|
248
|
+
const user = await User.find("user123"); // ✅
|
|
249
|
+
});
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
#### Context Detection API
|
|
253
|
+
|
|
254
|
+
You can check if code is currently running within a batch context:
|
|
255
|
+
|
|
256
|
+
```javascript
|
|
257
|
+
const { User } = require("./models/user");
|
|
258
|
+
|
|
259
|
+
// Check if inside batch context
|
|
260
|
+
const isInBatchContext = User.isInsideBatchContext();
|
|
261
|
+
|
|
262
|
+
if (isInBatchContext) {
|
|
263
|
+
// Full batching and caching available
|
|
264
|
+
console.log("Running with batching enabled");
|
|
265
|
+
} else {
|
|
266
|
+
// Direct execution mode
|
|
267
|
+
console.log("Running in direct execution mode");
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
#### Environment Variable Support
|
|
272
|
+
|
|
273
|
+
You can also configure batch context behavior via environment variables:
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
# Enable strict mode globally
|
|
277
|
+
export DYNAMO_BAO_REQUIRE_BATCH_CONTEXT=true
|
|
278
|
+
|
|
279
|
+
# Your application will now require runWithBatchContext for all operations
|
|
280
|
+
node your-app.js
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
This is particularly useful for:
|
|
284
|
+
|
|
285
|
+
- **Development/Testing**: Use strict mode to catch missing batch contexts early
|
|
286
|
+
- **Production**: Use default mode for maximum flexibility
|
|
287
|
+
- **Migration**: Gradually migrate from direct calls to batch context usage
|
|
187
288
|
|
|
188
289
|
### Iterating over all items
|
|
189
290
|
|
|
@@ -191,6 +292,8 @@ DynamoBao makes it easy to iterate over all items in a model, which is useful fo
|
|
|
191
292
|
|
|
192
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.
|
|
193
294
|
|
|
295
|
+
#### Basic Usage
|
|
296
|
+
|
|
194
297
|
```javascript
|
|
195
298
|
// Iterate over all posts, 100 at a time
|
|
196
299
|
for await (const batch of Post.iterateAll({ batchSize: 100 })) {
|
|
@@ -200,6 +303,78 @@ for await (const batch of Post.iterateAll({ batchSize: 100 })) {
|
|
|
200
303
|
}
|
|
201
304
|
```
|
|
202
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
|
+
|
|
203
378
|
**Cost and Performance**
|
|
204
379
|
|
|
205
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.
|
|
@@ -219,6 +394,13 @@ models:
|
|
|
219
394
|
# ...
|
|
220
395
|
```
|
|
221
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
|
+
|
|
222
404
|
## Installation / Quick Start
|
|
223
405
|
|
|
224
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.
|
|
@@ -421,3 +603,141 @@ It's worth noting that you didn't have to:
|
|
|
421
603
|
- Install a database (either locally or on a server)
|
|
422
604
|
- Understand how to generate keys and indexes using single table design princples
|
|
423
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/config.js
CHANGED
|
@@ -52,7 +52,7 @@ async function findConfig() {
|
|
|
52
52
|
tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
|
|
53
53
|
},
|
|
54
54
|
codegen: {
|
|
55
|
-
moduleSystem:
|
|
55
|
+
moduleSystem: "commonjs",
|
|
56
56
|
},
|
|
57
57
|
logging: {
|
|
58
58
|
level: process.env.LOG_LEVEL || "ERROR",
|
|
@@ -65,16 +65,20 @@ async function findConfig() {
|
|
|
65
65
|
tenancy: {
|
|
66
66
|
enabled: process.env.DYNAMO_BAO_TENANCY_ENABLED === "true" || false,
|
|
67
67
|
},
|
|
68
|
+
batchContext: {
|
|
69
|
+
requireBatchContext:
|
|
70
|
+
process.env.DYNAMO_BAO_REQUIRE_BATCH_CONTEXT === "true" || false,
|
|
71
|
+
},
|
|
68
72
|
};
|
|
69
73
|
}
|
|
70
74
|
|
|
71
75
|
async function loadConfigFile(configPath) {
|
|
72
|
-
if (configPath.endsWith(
|
|
76
|
+
if (configPath.endsWith(".cjs")) {
|
|
73
77
|
// Use require for CommonJS files
|
|
74
78
|
return require(configPath);
|
|
75
|
-
} else if (configPath.endsWith(
|
|
79
|
+
} else if (configPath.endsWith(".mjs") || configPath.endsWith(".js")) {
|
|
76
80
|
// Use dynamic import for ESM files
|
|
77
|
-
const fileUrl =
|
|
81
|
+
const fileUrl = "file://" + configPath;
|
|
78
82
|
const module = await import(fileUrl);
|
|
79
83
|
return module.default || module;
|
|
80
84
|
} else {
|
|
@@ -83,13 +87,12 @@ async function loadConfigFile(configPath) {
|
|
|
83
87
|
}
|
|
84
88
|
}
|
|
85
89
|
|
|
86
|
-
|
|
87
90
|
function normalizeConfig(rawConfig, configDir) {
|
|
88
91
|
return {
|
|
89
92
|
...rawConfig,
|
|
90
93
|
models: rawConfig.models || null,
|
|
91
94
|
codegen: {
|
|
92
|
-
moduleSystem:
|
|
95
|
+
moduleSystem: "commonjs",
|
|
93
96
|
...(rawConfig.codegen || {}),
|
|
94
97
|
},
|
|
95
98
|
paths: {
|
|
@@ -116,6 +119,10 @@ function normalizeConfig(rawConfig, configDir) {
|
|
|
116
119
|
enabled: false,
|
|
117
120
|
...rawConfig.tenancy,
|
|
118
121
|
},
|
|
122
|
+
batchContext: {
|
|
123
|
+
requireBatchContext: false,
|
|
124
|
+
...rawConfig.batchContext,
|
|
125
|
+
},
|
|
119
126
|
};
|
|
120
127
|
}
|
|
121
128
|
|
|
@@ -124,7 +131,7 @@ let config = null;
|
|
|
124
131
|
|
|
125
132
|
function getConfig() {
|
|
126
133
|
if (!config) {
|
|
127
|
-
throw new Error(
|
|
134
|
+
throw new Error("Config not initialized. Call initConfig() first.");
|
|
128
135
|
}
|
|
129
136
|
return config;
|
|
130
137
|
}
|
|
@@ -146,7 +153,7 @@ try {
|
|
|
146
153
|
tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
|
|
147
154
|
},
|
|
148
155
|
codegen: {
|
|
149
|
-
moduleSystem:
|
|
156
|
+
moduleSystem: "commonjs",
|
|
150
157
|
},
|
|
151
158
|
logging: {
|
|
152
159
|
level: process.env.LOG_LEVEL || "ERROR",
|
|
@@ -159,18 +166,23 @@ try {
|
|
|
159
166
|
tenancy: {
|
|
160
167
|
enabled: process.env.DYNAMO_BAO_TENANCY_ENABLED === "true" || false,
|
|
161
168
|
},
|
|
169
|
+
batchContext: {
|
|
170
|
+
requireBatchContext:
|
|
171
|
+
process.env.DYNAMO_BAO_REQUIRE_BATCH_CONTEXT === "true" || false,
|
|
172
|
+
},
|
|
162
173
|
};
|
|
163
174
|
} catch (err) {
|
|
164
|
-
console.error(
|
|
175
|
+
console.error("Error loading config:", err);
|
|
165
176
|
}
|
|
166
177
|
|
|
167
178
|
module.exports = config || {
|
|
168
179
|
aws: { region: "us-west-2" },
|
|
169
180
|
db: { tableName: "dynamo-bao-dev" },
|
|
170
|
-
codegen: { moduleSystem:
|
|
181
|
+
codegen: { moduleSystem: "commonjs" },
|
|
171
182
|
logging: { level: "ERROR" },
|
|
172
183
|
paths: { modelsDir: null },
|
|
173
|
-
tenancy: { enabled: false }
|
|
184
|
+
tenancy: { enabled: false },
|
|
185
|
+
batchContext: { requireBatchContext: false },
|
|
174
186
|
};
|
|
175
187
|
|
|
176
188
|
module.exports.initConfig = initConfig;
|