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,595 @@
1
+ const {
2
+ TransactWriteCommand,
3
+ UpdateCommand,
4
+ } = require("@aws-sdk/lib-dynamodb");
5
+ const { defaultLogger: logger } = require("../utils/logger");
6
+ const { pluginManager } = require("../plugin-manager");
7
+ const { retryOperation } = require("../utils/retry-helper");
8
+ const assert = require("assert");
9
+
10
+ const MutationMethods = {
11
+ /**
12
+ *@memberof BaoModel
13
+ * @description
14
+ * Create a new item in the database.
15
+ * @param {Object} jsUpdates - The data to create the item with.
16
+ * @returns {Promise<Object>} Returns a promise that resolves to the created item.
17
+ */
18
+ async create(jsUpdates) {
19
+ await pluginManager.executeHooks(this.name, "beforeSave", jsUpdates, {
20
+ isNew: true,
21
+ });
22
+ const result = await this._saveItem(null, jsUpdates, { isNew: true });
23
+
24
+ logger.debug("create() - result", result);
25
+ await pluginManager.executeHooks(this.name, "afterSave", result, {
26
+ isNew: true,
27
+ });
28
+ return result;
29
+ },
30
+
31
+ /**
32
+ *@memberof BaoModel
33
+ * @description
34
+ * Update an existing item in the database.
35
+ * @param {string} primaryId - The primary ID of the item to update.
36
+ * @param {Object} jsUpdates - The data to update the item with.
37
+ * @param {Object} [options] - Additional options for the update operation.
38
+ * @returns {Promise<Object>} Returns a promise that resolves to the updated item.
39
+ */
40
+ async update(primaryId, jsUpdates, options = {}) {
41
+ const updateOptions = {
42
+ isNew: false,
43
+ ...options,
44
+ };
45
+ await pluginManager.executeHooks(
46
+ this.name,
47
+ "beforeSave",
48
+ jsUpdates,
49
+ updateOptions,
50
+ );
51
+
52
+ const result = await this._saveItem(primaryId, jsUpdates, updateOptions);
53
+
54
+ logger.debug("update() - result", result);
55
+
56
+ await pluginManager.executeHooks(
57
+ this.name,
58
+ "afterSave",
59
+ result,
60
+ updateOptions,
61
+ );
62
+
63
+ return result;
64
+ },
65
+
66
+ /**
67
+ *@memberof BaoModel
68
+ * @description
69
+ * Delete an existing item in the database.
70
+ * @param {string} primaryId - The primary ID of the item to delete.
71
+ * @param {Object} [options] - Additional options for the delete operation.
72
+ * @returns {Promise<Object>} Returns a promise that resolves to the deleted item.
73
+ */
74
+ async delete(primaryId, options = {}) {
75
+ await pluginManager.executeHooks(
76
+ this.name,
77
+ "beforeDelete",
78
+ primaryId,
79
+ options,
80
+ );
81
+
82
+ const item = await this.find(primaryId, { batchDelay: 0 });
83
+ if (!item) {
84
+ throw new Error("Item not found");
85
+ }
86
+
87
+ const transactItems = [
88
+ {
89
+ Delete: {
90
+ TableName: this.table,
91
+ Key: {
92
+ _pk: item._dyData._pk,
93
+ _sk: item._dyData._sk,
94
+ },
95
+ },
96
+ },
97
+ ];
98
+
99
+ // Add unique constraint cleanup
100
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
101
+ if (uniqueConstraints.length > 0) {
102
+ for (const constraint of uniqueConstraints) {
103
+ const value = item[constraint.field];
104
+ if (value) {
105
+ const constraintOp = await this._removeUniqueConstraint(
106
+ constraint.field,
107
+ value,
108
+ item.getPrimaryId(),
109
+ constraint.constraintId,
110
+ );
111
+ transactItems.push(constraintOp);
112
+ }
113
+ }
114
+ }
115
+
116
+ const response = await retryOperation(() =>
117
+ this.documentClient.send(
118
+ new TransactWriteCommand({
119
+ TransactItems: transactItems,
120
+ ReturnConsumedCapacity: "TOTAL",
121
+ }),
122
+ ),
123
+ );
124
+
125
+ await pluginManager.executeHooks(
126
+ this.name,
127
+ "afterDelete",
128
+ primaryId,
129
+ options,
130
+ );
131
+
132
+ // Return deleted item info with capacity information
133
+ item._setConsumedCapacity(response.ConsumedCapacity, "write", false);
134
+ return item;
135
+ },
136
+
137
+ _createNewPrimaryId(jsUpdates) {
138
+ // Now calculate primary key values using the processed data
139
+ const pkValue = this._getPkValue(jsUpdates);
140
+ const skValue = this._getSkValue(jsUpdates);
141
+
142
+ // Format the primary key
143
+ const pk = this._formatPrimaryKey(this.modelPrefix, pkValue);
144
+ const primaryId = this.getPrimaryId({
145
+ ...jsUpdates,
146
+ _pk: pk,
147
+ _sk: skValue,
148
+ });
149
+
150
+ return primaryId;
151
+ },
152
+
153
+ /**
154
+ *@memberof BaoModel
155
+ * @private
156
+ * @description
157
+ * Save an item to the database.
158
+ * @param {string} primaryId - The primary ID of the item to save.
159
+ * @param {Object} jsUpdates - The data to save the item with.
160
+ * @param {Object} [options] - Additional options for the save operation.
161
+ * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
162
+ * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
163
+ * @param {Object} [options.constraints={}] - Constraints to validate. Options are:
164
+ * @param {boolean} [options.constraints.mustExist=false] - Whether the item must exist.
165
+ * @param {boolean} [options.constraints.mustNotExist=false] - Whether the item must not exist.
166
+ * @param {string[]} [options.constraints.fieldMatches=[]] - An array of field names that must match
167
+ * the current item's loaded state. This is often used for optimistic locking in conjunction
168
+ * with a {@link BaoFields.VersionField} field.
169
+ * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
170
+ */
171
+ async _saveItem(primaryId, jsUpdates, options = {}) {
172
+ try {
173
+ const { isNew = false, instanceObj = null, constraints = {} } = options;
174
+
175
+ logger.debug("saveItem", primaryId, isNew, instanceObj);
176
+ let consumedCapacity = [];
177
+
178
+ let currentItem = instanceObj;
179
+ if (isNew) {
180
+ currentItem = null;
181
+ } else if (!currentItem) {
182
+ currentItem = await this.find(primaryId, { batchDelay: 0 });
183
+ consumedCapacity = [
184
+ ...consumedCapacity,
185
+ ...currentItem.getConsumedCapacity(),
186
+ ];
187
+ }
188
+
189
+ if (!isNew && !currentItem) {
190
+ throw new Error("Item not found");
191
+ }
192
+
193
+ const transactItems = [];
194
+ const dyUpdatesToSave = {};
195
+ let hasUniqueConstraintChanges = false;
196
+
197
+ logger.debug("jsUpdates", jsUpdates);
198
+
199
+ // Generate Dynamo Updates to save
200
+ for (const [key, field] of Object.entries(this.fields)) {
201
+ if (isNew && jsUpdates[key] === undefined) {
202
+ // Only set initial values during creation
203
+ const initialValue = field.getInitialValue();
204
+ if (initialValue !== undefined) {
205
+ jsUpdates[key] = initialValue;
206
+ }
207
+ }
208
+
209
+ if (jsUpdates[key] !== undefined) {
210
+ field.validate(jsUpdates[key]);
211
+ dyUpdatesToSave[key] = field.toDy(jsUpdates[key]);
212
+ } else {
213
+ if (typeof field.updateBeforeSave === "function") {
214
+ const newValue = field.updateBeforeSave(jsUpdates[key]);
215
+ if (newValue !== jsUpdates[key]) {
216
+ dyUpdatesToSave[key] = field.toDy(newValue);
217
+ }
218
+ }
219
+ }
220
+ }
221
+
222
+ if (isNew) {
223
+ primaryId = this._createNewPrimaryId(jsUpdates);
224
+
225
+ // validate required fields
226
+ for (const [fieldName, field] of Object.entries(this.fields)) {
227
+ if (
228
+ field.required &&
229
+ (jsUpdates[fieldName] === undefined ||
230
+ jsUpdates[fieldName] === null)
231
+ ) {
232
+ throw new Error(`Field is required: ${fieldName} `);
233
+ }
234
+ }
235
+ }
236
+
237
+ Object.entries(jsUpdates).forEach(([fieldName, value]) => {
238
+ const field = this._getField(fieldName);
239
+ if (field) {
240
+ field.validate(value, fieldName);
241
+ }
242
+ });
243
+
244
+ // Validate unique constraints before attempting save
245
+ await this._validateUniqueConstraints(
246
+ jsUpdates,
247
+ isNew ? null : primaryId,
248
+ );
249
+
250
+ // Handle unique constraints
251
+ for (const constraint of Object.values(this.uniqueConstraints || {})) {
252
+ const fieldName = constraint.field;
253
+ const field = this._getField(fieldName);
254
+ const dyNewValue = dyUpdatesToSave[fieldName];
255
+ const dyCurrentValue = currentItem?._loadedDyData[fieldName];
256
+
257
+ logger.debug("uniqueConstraint", field, dyCurrentValue, dyNewValue);
258
+
259
+ if (dyNewValue !== undefined && dyNewValue !== dyCurrentValue) {
260
+ hasUniqueConstraintChanges = true;
261
+
262
+ // Remove old constraint if updating
263
+ if (currentItem && dyCurrentValue) {
264
+ transactItems.push(
265
+ await this._removeUniqueConstraint(
266
+ fieldName,
267
+ dyCurrentValue,
268
+ primaryId,
269
+ constraint.constraintId,
270
+ ),
271
+ );
272
+ }
273
+
274
+ // Add new constraint
275
+ transactItems.push(
276
+ await this._createUniqueConstraint(
277
+ fieldName,
278
+ dyNewValue,
279
+ primaryId,
280
+ constraint.constraintId,
281
+ ),
282
+ );
283
+ }
284
+ }
285
+
286
+ // Add testId if we're in test mode
287
+ const testId = this.manager.getTestId();
288
+ if (testId) {
289
+ logger.debug("savedTestId", testId, currentItem);
290
+ if (testId !== currentItem?._loadedDyData._gsi_test_id) {
291
+ dyUpdatesToSave._gsi_test_id = testId;
292
+ }
293
+ }
294
+
295
+ // Add GSI keys
296
+ const indexKeys = this._getIndexKeys(dyUpdatesToSave);
297
+ logger.debug("indexKeys", indexKeys);
298
+ Object.assign(dyUpdatesToSave, indexKeys);
299
+
300
+ // Build the condition expression for the update/put
301
+ const conditionExpressions = [];
302
+ const conditionNames = {};
303
+ const conditionValues = {};
304
+
305
+ // Handle existence constraints
306
+ if (constraints.mustExist) {
307
+ conditionExpressions.push("attribute_exists(#pk)");
308
+ conditionNames["#pk"] = "_pk";
309
+ }
310
+ if (constraints.mustNotExist) {
311
+ conditionExpressions.push("attribute_not_exists(#pk)");
312
+ conditionNames["#pk"] = "_pk";
313
+ }
314
+
315
+ logger.debug("field matchconstraints", constraints);
316
+
317
+ // Handle field match constraints
318
+ if (constraints.fieldMatches) {
319
+ if (instanceObj === null) {
320
+ throw new Error("Instance object is required to check field matches");
321
+ }
322
+
323
+ const matchFields = Array.isArray(constraints.fieldMatches)
324
+ ? constraints.fieldMatches
325
+ : [constraints.fieldMatches];
326
+
327
+ matchFields.forEach((fieldName, index) => {
328
+ if (!this._getField(fieldName)) {
329
+ throw new Error(
330
+ `Unknown field in fieldMatches constraint: ${fieldName}`,
331
+ );
332
+ }
333
+
334
+ const nameKey = `#match${index}`;
335
+ const valueKey = `:match${index}`;
336
+
337
+ conditionExpressions.push(`${nameKey} = ${valueKey}`);
338
+ conditionNames[nameKey] = fieldName;
339
+ conditionValues[valueKey] = currentItem
340
+ ? currentItem._loadedDyData[fieldName]
341
+ : undefined;
342
+ });
343
+ }
344
+
345
+ // When building update expression, pass both old and new data
346
+ const { updateExpression, names, values } =
347
+ this._buildUpdateExpression(dyUpdatesToSave);
348
+
349
+ const dyKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
350
+ logger.debug("dyKey", dyKey);
351
+
352
+ // Create the update params
353
+ const updateParams = {
354
+ TableName: this.table,
355
+ Key: dyKey,
356
+ UpdateExpression: updateExpression,
357
+ ExpressionAttributeNames: {
358
+ ...names,
359
+ ...conditionNames,
360
+ },
361
+ ReturnValues: "ALL_NEW",
362
+ };
363
+
364
+ if (Object.keys(values).length > 0) {
365
+ updateParams.ExpressionAttributeValues = {
366
+ ...values,
367
+ ...conditionValues,
368
+ };
369
+ }
370
+
371
+ // Add condition expression if we have any conditions
372
+ if (conditionExpressions.length > 0) {
373
+ updateParams.ConditionExpression = conditionExpressions.join(" AND ");
374
+ } else if (isNew) {
375
+ // Default condition for new items if no other conditions specified
376
+ updateParams.ConditionExpression = "attribute_not_exists(#pk)";
377
+ updateParams.ExpressionAttributeNames["#pk"] = "_pk";
378
+ }
379
+
380
+ try {
381
+ let response;
382
+
383
+ if (hasUniqueConstraintChanges) {
384
+ // Use transaction if we have unique constraint changes
385
+ transactItems.push({
386
+ Update: updateParams,
387
+ });
388
+
389
+ logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
390
+
391
+ response = await retryOperation(() =>
392
+ this.documentClient.send(
393
+ new TransactWriteCommand({
394
+ TransactItems: transactItems,
395
+ ReturnConsumedCapacity: "TOTAL",
396
+ }),
397
+ ),
398
+ );
399
+
400
+ logger.debug("transactItems response", response);
401
+ logger.debug("primaryId to load", primaryId);
402
+
403
+ // Fetch the item since transactWrite doesn't return values
404
+ const savedItem = await this.find(primaryId, { batchDelay: 0 });
405
+
406
+ logger.debug("savedItem", savedItem);
407
+ logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
408
+
409
+ if (!savedItem.exists()) {
410
+ throw new Error("Failed to fetch saved item");
411
+ }
412
+
413
+ // Set the consumed capacity from the transaction
414
+ savedItem._addConsumedCapacity(
415
+ response.ConsumedCapacity,
416
+ "write",
417
+ false,
418
+ );
419
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false);
420
+
421
+ return savedItem;
422
+ } else {
423
+ // Use simple update if no unique constraints are changing
424
+ logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
425
+
426
+ try {
427
+ response = await retryOperation(() =>
428
+ this.documentClient.send(
429
+ new UpdateCommand({
430
+ ...updateParams,
431
+ ReturnConsumedCapacity: "TOTAL",
432
+ }),
433
+ ),
434
+ );
435
+ } catch (error) {
436
+ logger.error(`DynamoDB update failed for ${primaryId}:`, error);
437
+ throw error;
438
+ }
439
+
440
+ const savedItem = this._createFromDyItem(response.Attributes);
441
+ logger.debug("savedItem", savedItem);
442
+
443
+ savedItem._setConsumedCapacity(
444
+ response.ConsumedCapacity,
445
+ "write",
446
+ false,
447
+ );
448
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false);
449
+ return savedItem;
450
+ }
451
+ } catch (error) {
452
+ logger.error("Error in _saveItem", error);
453
+ if (error.name === "ConditionalCheckFailedException") {
454
+ if (constraints.mustExist) {
455
+ throw new Error("Item must exist");
456
+ }
457
+ if (constraints.mustNotExist) {
458
+ throw new Error("Item must not exist");
459
+ }
460
+ if (constraints.fieldMatches) {
461
+ throw new Error("Field values have been modified");
462
+ }
463
+ throw new Error("Condition check failed", error);
464
+ }
465
+
466
+ if (error.name === "TransactionCanceledException") {
467
+ await this._validateUniqueConstraints(
468
+ jsUpdates,
469
+ isNew ? null : primaryId,
470
+ );
471
+ }
472
+ throw error;
473
+ }
474
+ } catch (error) {
475
+ logger.error(`Error in _saveItem for ${primaryId}:`, error);
476
+ throw error;
477
+ }
478
+ },
479
+
480
+ _buildUpdateExpression(dyUpdatesToSave) {
481
+ const names = {};
482
+ const values = {};
483
+ const expressions = [];
484
+
485
+ logger.debug("dyUpdatesToSave", dyUpdatesToSave);
486
+
487
+ // Process all fields in the data
488
+ for (const [fieldName, value] of Object.entries(dyUpdatesToSave)) {
489
+ // Skip undefined values
490
+ if (value === undefined) continue;
491
+
492
+ const field = this._getField(fieldName);
493
+
494
+ // Handle null values differently - use REMOVE instead of SET
495
+ if (value === null) {
496
+ expressions.push({
497
+ type: "REMOVE",
498
+ expression: `#${fieldName}`,
499
+ attrNameKey: `#${fieldName}`,
500
+ fieldName: fieldName,
501
+ fieldValue: null,
502
+ });
503
+ } else {
504
+ expressions.push(field.getUpdateExpression(fieldName, value));
505
+ }
506
+ }
507
+
508
+ const parts = [];
509
+ const setExpressions = [];
510
+ const addExpressions = [];
511
+ const removeExpressions = [];
512
+
513
+ expressions.forEach((expression) => {
514
+ if (expression.type === "SET") {
515
+ setExpressions.push(expression.expression);
516
+ } else if (expression.type === "ADD") {
517
+ addExpressions.push(expression.expression);
518
+ } else if (expression.type === "REMOVE") {
519
+ removeExpressions.push(expression.expression);
520
+ }
521
+
522
+ names[expression.attrNameKey] = expression.fieldName;
523
+
524
+ if (expression.fieldValue !== null) {
525
+ values[expression.attrValueKey] = expression.fieldValue;
526
+ }
527
+ });
528
+
529
+ if (setExpressions.length > 0)
530
+ parts.push(`SET ${setExpressions.join(", ")}`);
531
+ if (addExpressions.length > 0)
532
+ parts.push(`ADD ${addExpressions.join(", ")}`);
533
+ if (removeExpressions.length > 0)
534
+ parts.push(`REMOVE ${removeExpressions.join(", ")}`);
535
+
536
+ return {
537
+ updateExpression: parts.join(" "),
538
+ names,
539
+ values,
540
+ };
541
+ },
542
+
543
+ _getIndexKeys(data) {
544
+ const indexKeys = {};
545
+
546
+ Object.entries(this.indexes).forEach(([indexName, index]) => {
547
+ let pkValue, skValue;
548
+
549
+ // Handle partition key
550
+ if (index.pk === "modelPrefix") {
551
+ pkValue = this.modelPrefix;
552
+ } else {
553
+ const pkField = this._getField(index.pk);
554
+ pkValue = data[index.pk];
555
+ if (pkValue !== undefined) {
556
+ pkValue = pkField.toGsi(pkValue);
557
+ }
558
+ }
559
+
560
+ // Handle sort key
561
+ if (index.sk === "modelPrefix") {
562
+ skValue = this.modelPrefix;
563
+ } else {
564
+ const skField = this._getField(index.sk);
565
+ skValue = data[index.sk];
566
+ if (skValue !== undefined) {
567
+ skValue = skField.toGsi(skValue);
568
+ }
569
+ }
570
+
571
+ if (
572
+ pkValue !== undefined &&
573
+ skValue !== undefined &&
574
+ index.indexId !== undefined
575
+ ) {
576
+ logger.debug("indexKeys", {
577
+ pkValue,
578
+ skValue,
579
+ indexId: index.indexId,
580
+ });
581
+ const gsiPk = this._formatGsiKey(
582
+ this.modelPrefix,
583
+ index.indexId,
584
+ pkValue,
585
+ );
586
+ indexKeys[`_${index.indexId}_pk`] = gsiPk;
587
+ indexKeys[`_${index.indexId}_sk`] = skValue;
588
+ }
589
+ });
590
+
591
+ return indexKeys;
592
+ },
593
+ };
594
+
595
+ module.exports = MutationMethods;