dynamo-bao 0.2.12 → 0.3.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.
- package/README.md +102 -2
- package/package.json +1 -1
- package/src/config.js +23 -11
- package/src/index.js +4 -0
- package/src/mixins/batch-loading-mixin.js +107 -42
- package/src/model-manager.js +8 -2
- package/src/model.js +13 -25
package/README.md
CHANGED
|
@@ -181,9 +181,109 @@ export default {
|
|
|
181
181
|
**Request Isolation**:
|
|
182
182
|
|
|
183
183
|
- **With `runWithBatchContext`**: Each request gets its own isolated batch context with optimal batching performance
|
|
184
|
-
- **Without `runWithBatchContext`**:
|
|
184
|
+
- **Without `runWithBatchContext`**: Operations automatically fall back to direct execution (no batching/caching) to ensure request isolation
|
|
185
185
|
|
|
186
|
-
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and performance.
|
|
186
|
+
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and optimal performance.
|
|
187
|
+
|
|
188
|
+
### Batch Context Configuration
|
|
189
|
+
|
|
190
|
+
DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
|
|
191
|
+
|
|
192
|
+
#### Configuration Options
|
|
193
|
+
|
|
194
|
+
Add the `batchContext` configuration to your config file:
|
|
195
|
+
|
|
196
|
+
```javascript
|
|
197
|
+
// config.js or dynamo-bao.config.js
|
|
198
|
+
module.exports = {
|
|
199
|
+
aws: {
|
|
200
|
+
region: "us-west-2",
|
|
201
|
+
},
|
|
202
|
+
db: {
|
|
203
|
+
tableName: "your-table-name",
|
|
204
|
+
},
|
|
205
|
+
batchContext: {
|
|
206
|
+
requireBatchContext: false, // Default: allow fallback behavior
|
|
207
|
+
},
|
|
208
|
+
// ... other config
|
|
209
|
+
};
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
#### Behavior Modes
|
|
213
|
+
|
|
214
|
+
**Default Mode (`requireBatchContext: false`)**:
|
|
215
|
+
|
|
216
|
+
- Operations inside `runWithBatchContext`: Full batching and caching enabled
|
|
217
|
+
- Operations outside `runWithBatchContext`: Direct execution without batching or caching
|
|
218
|
+
- Provides maximum flexibility and backward compatibility
|
|
219
|
+
|
|
220
|
+
```javascript
|
|
221
|
+
// Works with direct execution (no batching/caching)
|
|
222
|
+
const user = await User.find("user123");
|
|
223
|
+
|
|
224
|
+
// Also works with batching + caching
|
|
225
|
+
await runWithBatchContext(async () => {
|
|
226
|
+
const user = await User.find("user123");
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Strict Mode (`requireBatchContext: true`)**:
|
|
231
|
+
|
|
232
|
+
- Operations inside `runWithBatchContext`: Full batching and caching enabled
|
|
233
|
+
- Operations outside `runWithBatchContext`: Throws an error
|
|
234
|
+
- Ensures all database operations use proper batch context
|
|
235
|
+
|
|
236
|
+
```javascript
|
|
237
|
+
// Configure strict mode
|
|
238
|
+
const manager = initModels({
|
|
239
|
+
batchContext: { requireBatchContext: true },
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// This throws an error
|
|
243
|
+
await User.find("user123"); // Error: Batch operations must be executed within runWithBatchContext()
|
|
244
|
+
|
|
245
|
+
// This works
|
|
246
|
+
await runWithBatchContext(async () => {
|
|
247
|
+
const user = await User.find("user123"); // ✅
|
|
248
|
+
});
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
#### Context Detection API
|
|
252
|
+
|
|
253
|
+
You can check if code is currently running within a batch context:
|
|
254
|
+
|
|
255
|
+
```javascript
|
|
256
|
+
const { User } = require("./models/user");
|
|
257
|
+
|
|
258
|
+
// Check if inside batch context
|
|
259
|
+
const isInBatchContext = User.isInsideBatchContext();
|
|
260
|
+
|
|
261
|
+
if (isInBatchContext) {
|
|
262
|
+
// Full batching and caching available
|
|
263
|
+
console.log("Running with batching enabled");
|
|
264
|
+
} else {
|
|
265
|
+
// Direct execution mode
|
|
266
|
+
console.log("Running in direct execution mode");
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
#### Environment Variable Support
|
|
271
|
+
|
|
272
|
+
You can also configure batch context behavior via environment variables:
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
# Enable strict mode globally
|
|
276
|
+
export DYNAMO_BAO_REQUIRE_BATCH_CONTEXT=true
|
|
277
|
+
|
|
278
|
+
# Your application will now require runWithBatchContext for all operations
|
|
279
|
+
node your-app.js
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
This is particularly useful for:
|
|
283
|
+
|
|
284
|
+
- **Development/Testing**: Use strict mode to catch missing batch contexts early
|
|
285
|
+
- **Production**: Use default mode for maximum flexibility
|
|
286
|
+
- **Migration**: Gradually migrate from direct calls to batch context usage
|
|
187
287
|
|
|
188
288
|
### Iterating over all items
|
|
189
289
|
|
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;
|
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
|
};
|
package/src/model-manager.js
CHANGED
|
@@ -13,6 +13,7 @@ class ModelManager {
|
|
|
13
13
|
this._tenantId = null; // Changed from _testId
|
|
14
14
|
this._tenancyEnabled = false;
|
|
15
15
|
this._models = new Map();
|
|
16
|
+
this._config = null; // Store config for models to access
|
|
16
17
|
}
|
|
17
18
|
|
|
18
19
|
static getInstance(tenantId = null) {
|
|
@@ -27,16 +28,19 @@ class ModelManager {
|
|
|
27
28
|
|
|
28
29
|
async init(config = {}) {
|
|
29
30
|
// Validate tenant requirement
|
|
30
|
-
const { TenantContext } = require(
|
|
31
|
+
const { TenantContext } = require("./tenant-context");
|
|
31
32
|
TenantContext.validateTenantRequired(config);
|
|
32
33
|
|
|
34
|
+
// Store config for models to access
|
|
35
|
+
this._config = config;
|
|
36
|
+
|
|
33
37
|
const client = new DynamoDBClient({
|
|
34
38
|
region: config.aws.region,
|
|
35
39
|
});
|
|
36
40
|
this._docClient = DynamoDBDocumentClient.from(client);
|
|
37
41
|
this._tableName = config.db.tableName;
|
|
38
42
|
this._tenancyEnabled = config.tenancy?.enabled || false;
|
|
39
|
-
|
|
43
|
+
|
|
40
44
|
// Support both tenantId and testId for backward compatibility
|
|
41
45
|
this._tenantId = config.tenantId || config.testId || this._tenantId;
|
|
42
46
|
|
|
@@ -46,6 +50,7 @@ class ModelManager {
|
|
|
46
50
|
ModelClass._testId = this._tenantId; // Backward compatibility
|
|
47
51
|
ModelClass.documentClient = this._docClient;
|
|
48
52
|
ModelClass.table = this._tableName;
|
|
53
|
+
ModelClass._config = config; // Pass config to models
|
|
49
54
|
ModelClass._validateConfiguration();
|
|
50
55
|
}
|
|
51
56
|
|
|
@@ -88,6 +93,7 @@ class ModelManager {
|
|
|
88
93
|
if (this._initialized) {
|
|
89
94
|
ModelClass.documentClient = this._docClient;
|
|
90
95
|
ModelClass.table = this._tableName;
|
|
96
|
+
ModelClass._config = this._config; // Pass config to newly registered models
|
|
91
97
|
ModelClass._validateConfiguration();
|
|
92
98
|
}
|
|
93
99
|
|
package/src/model.js
CHANGED
|
@@ -233,20 +233,18 @@ class BaoModel {
|
|
|
233
233
|
throw new Error(`Model ${this.name} is not configured as iterable`);
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
const { batchSize = 100, filter = null
|
|
236
|
+
const { batchSize = 100, filter = null } = options;
|
|
237
237
|
|
|
238
238
|
if (this.iterationBuckets === 1) {
|
|
239
239
|
yield* this._iterateSingleBucket(null, {
|
|
240
240
|
batchSize,
|
|
241
241
|
filter,
|
|
242
|
-
loaderContext,
|
|
243
242
|
});
|
|
244
243
|
} else {
|
|
245
244
|
for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
|
|
246
245
|
yield* this._iterateSingleBucket(bucket, {
|
|
247
246
|
batchSize,
|
|
248
247
|
filter,
|
|
249
|
-
loaderContext,
|
|
250
248
|
});
|
|
251
249
|
}
|
|
252
250
|
}
|
|
@@ -267,7 +265,7 @@ class BaoModel {
|
|
|
267
265
|
}
|
|
268
266
|
|
|
269
267
|
static async *_iterateSingleBucket(bucketNum, options = {}) {
|
|
270
|
-
const { batchSize = 100, filter = null
|
|
268
|
+
const { batchSize = 100, filter = null } = options;
|
|
271
269
|
const tenantId = this.manager.getTenantId();
|
|
272
270
|
|
|
273
271
|
let iterPk;
|
|
@@ -324,7 +322,7 @@ class BaoModel {
|
|
|
324
322
|
(item) => item[ITERATION_SK_FIELD],
|
|
325
323
|
);
|
|
326
324
|
|
|
327
|
-
const { items } = await this.batchFind(objectIds
|
|
325
|
+
const { items } = await this.batchFind(objectIds);
|
|
328
326
|
const batch = Object.values(items);
|
|
329
327
|
|
|
330
328
|
if (batch.length > 0) {
|
|
@@ -619,7 +617,7 @@ class BaoModel {
|
|
|
619
617
|
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
620
618
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded item.
|
|
621
619
|
*/
|
|
622
|
-
async getOrLoadRelatedField(fieldName
|
|
620
|
+
async getOrLoadRelatedField(fieldName) {
|
|
623
621
|
if (this._relatedObjects[fieldName]) {
|
|
624
622
|
return this._relatedObjects[fieldName];
|
|
625
623
|
}
|
|
@@ -636,9 +634,7 @@ class BaoModel {
|
|
|
636
634
|
if (!value) return null;
|
|
637
635
|
|
|
638
636
|
const ModelClass = this.constructor.manager.getModel(field.modelName);
|
|
639
|
-
this._relatedObjects[fieldName] = await ModelClass.find(value
|
|
640
|
-
loaderContext,
|
|
641
|
-
});
|
|
637
|
+
this._relatedObjects[fieldName] = await ModelClass.find(value);
|
|
642
638
|
return this._relatedObjects[fieldName];
|
|
643
639
|
}
|
|
644
640
|
|
|
@@ -646,10 +642,9 @@ class BaoModel {
|
|
|
646
642
|
* @description
|
|
647
643
|
* Load objects for RelatedField's on the current model instance.
|
|
648
644
|
* @param {string[]} [fieldNames] - The names of the fields to load. If not provided, all related fields will be loaded.
|
|
649
|
-
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
650
645
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
651
646
|
*/
|
|
652
|
-
async loadRelatedData(fieldNames = null
|
|
647
|
+
async loadRelatedData(fieldNames = null) {
|
|
653
648
|
const promises = [];
|
|
654
649
|
|
|
655
650
|
for (const [fieldName, field] of Object.entries(this.constructor.fields)) {
|
|
@@ -659,11 +654,9 @@ class BaoModel {
|
|
|
659
654
|
|
|
660
655
|
if (field instanceof RelatedFieldClass && this[fieldName]) {
|
|
661
656
|
promises.push(
|
|
662
|
-
this._loadRelatedField(fieldName, field
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
},
|
|
666
|
-
),
|
|
657
|
+
this._loadRelatedField(fieldName, field).then((instance) => {
|
|
658
|
+
this._relatedObjects[fieldName] = instance;
|
|
659
|
+
}),
|
|
667
660
|
);
|
|
668
661
|
}
|
|
669
662
|
}
|
|
@@ -672,7 +665,7 @@ class BaoModel {
|
|
|
672
665
|
return this;
|
|
673
666
|
}
|
|
674
667
|
|
|
675
|
-
async _loadRelatedField(fieldName, field
|
|
668
|
+
async _loadRelatedField(fieldName, field) {
|
|
676
669
|
const value = this[fieldName];
|
|
677
670
|
if (!value) return null;
|
|
678
671
|
|
|
@@ -683,7 +676,7 @@ class BaoModel {
|
|
|
683
676
|
}
|
|
684
677
|
|
|
685
678
|
// Load the instance and track its capacity
|
|
686
|
-
const relatedInstance = await ModelClass.find(value
|
|
679
|
+
const relatedInstance = await ModelClass.find(value);
|
|
687
680
|
|
|
688
681
|
return relatedInstance;
|
|
689
682
|
}
|
|
@@ -711,14 +704,9 @@ class BaoModel {
|
|
|
711
704
|
* to find an object.
|
|
712
705
|
* @param {string} constraintName - The name of the unique constraint to use.
|
|
713
706
|
* @param {string} value - The value of the unique constraint.
|
|
714
|
-
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
715
707
|
* @returns {Promise<Object>} Returns a promise that resolves to the found item.
|
|
716
708
|
*/
|
|
717
|
-
static async findByUniqueConstraint(
|
|
718
|
-
constraintName,
|
|
719
|
-
value,
|
|
720
|
-
loaderContext = null,
|
|
721
|
-
) {
|
|
709
|
+
static async findByUniqueConstraint(constraintName, value) {
|
|
722
710
|
const constraint = this.uniqueConstraints[constraintName];
|
|
723
711
|
if (!constraint) {
|
|
724
712
|
throw new ConfigurationError(
|
|
@@ -757,7 +745,7 @@ class BaoModel {
|
|
|
757
745
|
return new ObjectNotFound(result.ConsumedCapacity);
|
|
758
746
|
}
|
|
759
747
|
|
|
760
|
-
const item = await this.find(result.Item.relatedId
|
|
748
|
+
const item = await this.find(result.Item.relatedId);
|
|
761
749
|
|
|
762
750
|
if (item.exists()) {
|
|
763
751
|
item._addConsumedCapacity(result.ConsumedCapacity, "read");
|