dynamo-bao 0.9.0 → 0.11.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.
@@ -18,6 +18,21 @@ const {
18
18
  } = require("../exceptions");
19
19
  const { computeSearchTextUpdate } = require("../utils/search-text");
20
20
  const { SEARCH_TEXT_FIELD, GID_SEPARATOR } = require("../constants");
21
+ const { TRANSACT_OP } = require("../transact");
22
+
23
+ function withReturnValuesOnFailure(transactItem) {
24
+ const [action] = Object.keys(transactItem);
25
+ const params = transactItem[action];
26
+ if (params && params.ConditionExpression) {
27
+ return {
28
+ [action]: {
29
+ ...params,
30
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
31
+ },
32
+ };
33
+ }
34
+ return transactItem;
35
+ }
21
36
 
22
37
  /**
23
38
  * AND a guard onto an optional ConditionExpression. The existing expression
@@ -51,16 +66,26 @@ const MutationMethods = {
51
66
  * @param {Object} jsUpdates - The data to create the item with.
52
67
  * @returns {Promise<Object>} Returns a promise that resolves to the created item.
53
68
  */
54
- async create(jsUpdates) {
55
- await pluginManager.executeHooks(this.name, "beforeSave", jsUpdates, {
69
+ async create(jsUpdates, options = {}) {
70
+ const createOptions = {
56
71
  isNew: true,
57
- });
58
- const result = await this._saveItem(null, jsUpdates, { isNew: true });
72
+ ...options,
73
+ };
74
+ await pluginManager.executeHooks(
75
+ this.name,
76
+ "beforeSave",
77
+ jsUpdates,
78
+ createOptions,
79
+ );
80
+ const result = await this._saveItem(null, jsUpdates, createOptions);
59
81
 
60
82
  logger.debug("create() - result", result);
61
- await pluginManager.executeHooks(this.name, "afterSave", result, {
62
- isNew: true,
63
- });
83
+ await pluginManager.executeHooks(
84
+ this.name,
85
+ "afterSave",
86
+ result,
87
+ createOptions,
88
+ );
64
89
  return result;
65
90
  },
66
91
 
@@ -110,6 +135,91 @@ const MutationMethods = {
110
135
  return result;
111
136
  },
112
137
 
138
+ /**
139
+ * @private
140
+ */
141
+ async _prepareDelete(primaryId, options = {}) {
142
+ const canonicalId = this._canonicalPrimaryId(primaryId);
143
+
144
+ // The row is read first only when the delete needs its contents: to
145
+ // find unique-constraint values to clean up, or (mid key migration) to
146
+ // learn which key shape the row actually lives at. Otherwise the key is
147
+ // derived from the id and a single conditional DeleteItem does the work.
148
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
149
+ const needsRead =
150
+ uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
151
+
152
+ let item = null;
153
+ let key;
154
+ if (needsRead) {
155
+ item = await this.find(primaryId, { batchDelay: 0 });
156
+ if (!item.exists()) {
157
+ throw new ItemNotFoundError("Item not found", primaryId);
158
+ }
159
+ key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
160
+ } else {
161
+ key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
162
+ }
163
+
164
+ const deleteParams = {
165
+ TableName: this.table,
166
+ Key: key,
167
+ };
168
+
169
+ if (options.condition) {
170
+ const builder = new FilterExpressionBuilder();
171
+ const filterExpression = builder.build(options.condition, this);
172
+
173
+ if (filterExpression) {
174
+ deleteParams.ConditionExpression = filterExpression.FilterExpression;
175
+ deleteParams.ExpressionAttributeNames =
176
+ filterExpression.ExpressionAttributeNames;
177
+ deleteParams.ExpressionAttributeValues =
178
+ filterExpression.ExpressionAttributeValues;
179
+ }
180
+ }
181
+
182
+ let existsGuard = false;
183
+ if (!item) {
184
+ this._addExistsGuard(deleteParams);
185
+ existsGuard = true;
186
+ }
187
+
188
+ const uniqueTransactItems = [];
189
+ const uniqueItemMeta = [];
190
+ if (item !== null) {
191
+ for (const constraint of uniqueConstraints) {
192
+ const value = item[constraint.field];
193
+ if (value) {
194
+ const constraintOp = await this._removeUniqueConstraint(
195
+ constraint.field,
196
+ value,
197
+ item.getPrimaryId(),
198
+ constraint.constraintId,
199
+ );
200
+ uniqueTransactItems.push(constraintOp);
201
+ uniqueItemMeta.push({
202
+ role: "unique_delete",
203
+ constraintField: constraint.field,
204
+ hasExistsGuard: false,
205
+ });
206
+ }
207
+ }
208
+ }
209
+
210
+ const hasConstraintsToClean = uniqueTransactItems.length > 0;
211
+
212
+ return {
213
+ canonicalId,
214
+ item,
215
+ hasConstraintsToClean,
216
+ deleteParams,
217
+ existsGuard,
218
+ uniqueTransactItems,
219
+ uniqueItemMeta,
220
+ };
221
+ },
222
+
113
223
  /**
114
224
  *@memberof BaoModel
115
225
  * @description
@@ -150,33 +260,8 @@ const MutationMethods = {
150
260
  options,
151
261
  );
152
262
 
153
- // The row is read first only when the delete needs its contents: to
154
- // find unique-constraint values to clean up, or (mid key migration) to
155
- // learn which key shape the row actually lives at. Otherwise the key is
156
- // derived from the id and a single conditional DeleteItem does the work.
157
- const uniqueConstraints = Object.values(this.uniqueConstraints || {});
158
- const needsRead =
159
- uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
160
-
161
- let item = null;
162
- let key;
163
- if (needsRead) {
164
- item = await this.find(primaryId, { batchDelay: 0 });
165
- if (!item.exists()) {
166
- throw new ItemNotFoundError("Item not found", primaryId);
167
- }
168
- key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
169
- } else {
170
- key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
171
- }
172
-
173
- // Check if we need to clean up any unique constraints
174
- const hasConstraintsToClean =
175
- item !== null &&
176
- uniqueConstraints.some((constraint) => {
177
- const value = item[constraint.field];
178
- return value != null;
179
- });
263
+ const { item, hasConstraintsToClean, deleteParams, uniqueTransactItems } =
264
+ await this._prepareDelete(primaryId, options);
180
265
 
181
266
  try {
182
267
  let response;
@@ -184,45 +269,10 @@ const MutationMethods = {
184
269
  if (hasConstraintsToClean) {
185
270
  // Transaction path - handle unique constraint cleanup
186
271
  const transactItems = [
187
- {
188
- Delete: {
189
- TableName: this.table,
190
- Key: key,
191
- },
192
- },
272
+ { Delete: deleteParams },
273
+ ...uniqueTransactItems,
193
274
  ];
194
275
 
195
- // Add condition if specified
196
- if (options.condition) {
197
- const builder = new FilterExpressionBuilder();
198
- const filterExpression = builder.build(options.condition, this);
199
-
200
- if (filterExpression) {
201
- transactItems[0].Delete = {
202
- ...transactItems[0].Delete,
203
- ConditionExpression: filterExpression.FilterExpression,
204
- ExpressionAttributeNames:
205
- filterExpression.ExpressionAttributeNames,
206
- ExpressionAttributeValues:
207
- filterExpression.ExpressionAttributeValues,
208
- };
209
- }
210
- }
211
-
212
- // Add unique constraint cleanup operations
213
- for (const constraint of uniqueConstraints) {
214
- const value = item[constraint.field];
215
- if (value) {
216
- const constraintOp = await this._removeUniqueConstraint(
217
- constraint.field,
218
- value,
219
- item.getPrimaryId(),
220
- constraint.constraintId,
221
- );
222
- transactItems.push(constraintOp);
223
- }
224
- }
225
-
226
276
  // The token makes a retry after a lost response a no-op instead of
227
277
  // applying the transaction twice.
228
278
  const clientRequestToken = ulid();
@@ -237,36 +287,14 @@ const MutationMethods = {
237
287
  );
238
288
  } else {
239
289
  // Fast path - simple delete
240
- const deleteParams = {
241
- TableName: this.table,
242
- Key: key,
243
- ReturnValues: "ALL_OLD",
244
- ReturnConsumedCapacity: "TOTAL",
245
- };
246
-
247
- // Add condition if specified
248
- if (options.condition) {
249
- const builder = new FilterExpressionBuilder();
250
- const filterExpression = builder.build(options.condition, this);
251
-
252
- if (filterExpression) {
253
- deleteParams.ConditionExpression =
254
- filterExpression.FilterExpression;
255
- deleteParams.ExpressionAttributeNames =
256
- filterExpression.ExpressionAttributeNames;
257
- deleteParams.ExpressionAttributeValues =
258
- filterExpression.ExpressionAttributeValues;
259
- }
260
- }
261
-
262
- // Without a pre-read, the item's existence is checked by the delete
263
- // itself; a failure is mapped to ItemNotFoundError in the catch below.
264
- if (!item) {
265
- this._addExistsGuard(deleteParams);
266
- }
267
-
268
290
  response = await retryOperation(() =>
269
- this.documentClient.send(new DeleteCommand(deleteParams)),
291
+ this.documentClient.send(
292
+ new DeleteCommand({
293
+ ...deleteParams,
294
+ ReturnValues: "ALL_OLD",
295
+ ReturnConsumedCapacity: "TOTAL",
296
+ }),
297
+ ),
270
298
  );
271
299
  }
272
300
 
@@ -545,18 +573,308 @@ const MutationMethods = {
545
573
  },
546
574
 
547
575
  /**
548
- *@memberof BaoModel
549
- * @private
576
+ * @memberof BaoModel
550
577
  * @description
551
- * Save an item to the database.
552
- * @param {string} primaryId - The primary ID of the item to save.
553
- * @param {Object} jsUpdates - The data to save the item with.
554
- * @param {Object} [options] - Additional options for the save operation.
555
- * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
556
- * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
557
- * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
578
+ * Build a deferred create operation for use with {@link transact}.
579
+ * @param {Object} jsUpdates - Data to create the item with.
580
+ * @param {Object} [options] - Optional condition options.
581
+ * @returns {Object} Op descriptor for transact().
558
582
  */
559
- async _saveItem(primaryId, jsUpdates, options = {}) {
583
+ createOp(jsUpdates, options = {}) {
584
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
585
+ throw new ValidationError("createOp() requires a data object");
586
+ }
587
+ const tenantId = this.manager.getTenantId();
588
+ const model = this;
589
+ const table = this.table;
590
+ const documentClient = this.documentClient;
591
+ const dataCopy = { ...jsUpdates };
592
+ const opOptions = { ...options };
593
+
594
+ return {
595
+ [TRANSACT_OP]: true,
596
+ type: "create",
597
+ model,
598
+ tenantId,
599
+ table,
600
+ documentClient,
601
+ async _prepare() {
602
+ const hookOptions = { isNew: true, ...opOptions };
603
+ const working = { ...dataCopy };
604
+ await pluginManager.executeHooks(
605
+ model.name,
606
+ "beforeSave",
607
+ working,
608
+ hookOptions,
609
+ );
610
+ const prepared = await model._prepareSave(null, working, hookOptions);
611
+ const transactItems = [
612
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
613
+ withReturnValuesOnFailure({ Update: prepared.updateParams }),
614
+ ];
615
+ const itemMeta = [
616
+ ...prepared.uniqueItemMeta,
617
+ { role: "main", hasExistsGuard: false },
618
+ ];
619
+ const localResult = model._buildLocalSavedItem(
620
+ true,
621
+ null,
622
+ prepared.dyKey,
623
+ prepared.dyUpdatesToSave,
624
+ );
625
+ return {
626
+ type: "create",
627
+ model,
628
+ tenantId,
629
+ primaryId: prepared.primaryId,
630
+ transactItems,
631
+ itemMeta,
632
+ localResult,
633
+ hookOptions,
634
+ hasAtomicOps: prepared.hasAtomicOps,
635
+ };
636
+ },
637
+ };
638
+ },
639
+
640
+ /**
641
+ * @memberof BaoModel
642
+ * @description
643
+ * Build a deferred update operation for use with {@link transact}.
644
+ * @param {string|Object} primaryId - Primary ID of the item to update.
645
+ * @param {Object} jsUpdates - Changes to apply.
646
+ * @param {Object} [options] - Same options as {@link BaoModel.update}.
647
+ * @returns {Object} Op descriptor for transact().
648
+ */
649
+ updateOp(primaryId, jsUpdates, options = {}) {
650
+ if (primaryId === undefined || primaryId === null) {
651
+ throw new ValidationError("updateOp() requires a primaryId");
652
+ }
653
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
654
+ throw new ValidationError("updateOp() requires an updates object");
655
+ }
656
+ const tenantId = this.manager.getTenantId();
657
+ const model = this;
658
+ const table = this.table;
659
+ const documentClient = this.documentClient;
660
+ const updatesCopy = { ...jsUpdates };
661
+ const opOptions = { ...options };
662
+
663
+ return {
664
+ [TRANSACT_OP]: true,
665
+ type: "update",
666
+ model,
667
+ tenantId,
668
+ table,
669
+ documentClient,
670
+ async _prepare() {
671
+ const hookOptions = { isNew: false, ...opOptions };
672
+ const working = { ...updatesCopy };
673
+ await pluginManager.executeHooks(
674
+ model.name,
675
+ "beforeSave",
676
+ working,
677
+ hookOptions,
678
+ );
679
+ const prepared = await model._prepareSave(
680
+ primaryId,
681
+ working,
682
+ hookOptions,
683
+ );
684
+ const transactItems = [
685
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
686
+ withReturnValuesOnFailure({ Update: prepared.updateParams }),
687
+ ];
688
+ const itemMeta = [
689
+ ...prepared.uniqueItemMeta,
690
+ { role: "main", hasExistsGuard: prepared.existsGuard },
691
+ ];
692
+ const localResult =
693
+ prepared.currentItem && !prepared.hasAtomicOps
694
+ ? model._buildLocalSavedItem(
695
+ false,
696
+ prepared.currentItem,
697
+ prepared.dyKey,
698
+ prepared.dyUpdatesToSave,
699
+ )
700
+ : null;
701
+ return {
702
+ type: "update",
703
+ model,
704
+ tenantId,
705
+ primaryId: prepared.primaryId,
706
+ transactItems,
707
+ itemMeta,
708
+ localResult,
709
+ hookOptions,
710
+ hasAtomicOps: prepared.hasAtomicOps,
711
+ };
712
+ },
713
+ };
714
+ },
715
+
716
+ /**
717
+ * @memberof BaoModel
718
+ * @description
719
+ * Build a deferred delete operation for use with {@link transact}.
720
+ * @param {string|Object} primaryId - Primary ID of the item to delete.
721
+ * @param {Object} [options] - Same options as {@link BaoModel.delete}.
722
+ * @returns {Object} Op descriptor for transact().
723
+ */
724
+ deleteOp(primaryId, options = {}) {
725
+ if (primaryId === undefined || primaryId === null) {
726
+ throw new ValidationError("deleteOp() requires a primaryId");
727
+ }
728
+ const tenantId = this.manager.getTenantId();
729
+ const model = this;
730
+ const table = this.table;
731
+ const documentClient = this.documentClient;
732
+ const opOptions = { ...options };
733
+
734
+ return {
735
+ [TRANSACT_OP]: true,
736
+ type: "delete",
737
+ model,
738
+ tenantId,
739
+ table,
740
+ documentClient,
741
+ async _prepare() {
742
+ const canonicalId = model._canonicalPrimaryId(primaryId);
743
+ await pluginManager.executeHooks(
744
+ model.name,
745
+ "beforeDelete",
746
+ canonicalId,
747
+ opOptions,
748
+ );
749
+ const prepared = await model._prepareDelete(primaryId, opOptions);
750
+ const transactItems = [
751
+ withReturnValuesOnFailure({ Delete: prepared.deleteParams }),
752
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
753
+ ];
754
+ const itemMeta = [
755
+ { role: "main", hasExistsGuard: prepared.existsGuard },
756
+ ...prepared.uniqueItemMeta,
757
+ ];
758
+ return {
759
+ type: "delete",
760
+ model,
761
+ tenantId,
762
+ primaryId: prepared.canonicalId,
763
+ transactItems,
764
+ itemMeta,
765
+ localResult: prepared.item,
766
+ hookOptions: opOptions,
767
+ hasAtomicOps: false,
768
+ };
769
+ },
770
+ };
771
+ },
772
+
773
+ /**
774
+ * @memberof BaoModel
775
+ * @description
776
+ * Build a deferred ConditionCheck (read-only assertion) for use with {@link transact}.
777
+ * @param {string|Object} primaryId - Primary ID of the item to check.
778
+ * @param {Object} condition - Filter-style condition that must hold.
779
+ * @returns {Object} Op descriptor for transact().
780
+ */
781
+ conditionCheckOp(primaryId, condition) {
782
+ if (primaryId === undefined || primaryId === null) {
783
+ throw new ValidationError("conditionCheckOp() requires a primaryId");
784
+ }
785
+ if (
786
+ !condition ||
787
+ typeof condition !== "object" ||
788
+ Array.isArray(condition) ||
789
+ Object.keys(condition).length === 0
790
+ ) {
791
+ throw new ValidationError(
792
+ "conditionCheckOp() requires a non-empty condition object",
793
+ );
794
+ }
795
+ const tenantId = this.manager.getTenantId();
796
+ const model = this;
797
+ const table = this.table;
798
+ const documentClient = this.documentClient;
799
+
800
+ return {
801
+ [TRANSACT_OP]: true,
802
+ type: "conditionCheck",
803
+ model,
804
+ tenantId,
805
+ table,
806
+ documentClient,
807
+ async _prepare() {
808
+ const canonicalId = model._canonicalPrimaryId(primaryId);
809
+ let key;
810
+ if (model._writesInPlaceWhileMigrating()) {
811
+ const existing = await model.find(canonicalId, { batchDelay: 0 });
812
+ key = existing.exists()
813
+ ? { _pk: existing._dyData._pk, _sk: existing._dyData._sk }
814
+ : model._getDyKeyForPkSk(model._parsePrimaryId(canonicalId));
815
+ } else {
816
+ key = model._getDyKeyForPkSk(model._parsePrimaryId(canonicalId));
817
+ }
818
+
819
+ const builder = new FilterExpressionBuilder();
820
+ const filterExpression = builder.build(condition, model);
821
+ if (!filterExpression) {
822
+ throw new ValidationError(
823
+ "conditionCheckOp() requires a non-empty condition object",
824
+ );
825
+ }
826
+
827
+ const checkParams = {
828
+ TableName: model.table,
829
+ Key: key,
830
+ ConditionExpression: filterExpression.FilterExpression,
831
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
832
+ };
833
+ if (Object.keys(filterExpression.ExpressionAttributeNames).length > 0) {
834
+ checkParams.ExpressionAttributeNames =
835
+ filterExpression.ExpressionAttributeNames;
836
+ }
837
+ if (
838
+ Object.keys(filterExpression.ExpressionAttributeValues).length > 0
839
+ ) {
840
+ checkParams.ExpressionAttributeValues =
841
+ filterExpression.ExpressionAttributeValues;
842
+ }
843
+
844
+ return {
845
+ type: "conditionCheck",
846
+ model,
847
+ tenantId,
848
+ primaryId: canonicalId,
849
+ transactItems: [{ ConditionCheck: checkParams }],
850
+ itemMeta: [{ role: "main", hasExistsGuard: false }],
851
+ localResult: null,
852
+ hookOptions: null,
853
+ hasAtomicOps: false,
854
+ };
855
+ },
856
+ };
857
+ },
858
+
859
+ _buildLocalSavedItem(isNew, currentItem, dyKey, dyUpdatesToSave) {
860
+ const base = isNew
861
+ ? {}
862
+ : currentItem.isLoaded()
863
+ ? currentItem._loadedDyData
864
+ : currentItem._dyData;
865
+ const storedItem = { ...base, ...dyKey };
866
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
867
+ if (value === undefined) continue;
868
+ if (value === null) {
869
+ delete storedItem[key];
870
+ } else {
871
+ storedItem[key] = value;
872
+ }
873
+ }
874
+ return this._createFromDyItem(storedItem);
875
+ },
876
+
877
+ async _prepareSave(primaryId, jsUpdates, options = {}) {
560
878
  const { isNew = false, instanceObj = null, forceReindex = false } = options;
561
879
 
562
880
  // The id is used as a string below (iteration keys, the relatedId on
@@ -570,7 +888,8 @@ const MutationMethods = {
570
888
 
571
889
  let currentItem = isNew ? null : instanceObj;
572
890
 
573
- const transactItems = [];
891
+ const uniqueTransactItems = [];
892
+ const uniqueItemMeta = [];
574
893
  const dyUpdatesToSave = {};
575
894
  const indexComputationData = {};
576
895
  let hasUniqueConstraintChanges = false;
@@ -760,7 +1079,7 @@ const MutationMethods = {
760
1079
 
761
1080
  // Remove old constraint if updating
762
1081
  if (currentItem && dyCurrentValue) {
763
- transactItems.push(
1082
+ uniqueTransactItems.push(
764
1083
  await this._removeUniqueConstraint(
765
1084
  fieldName,
766
1085
  dyCurrentValue,
@@ -768,11 +1087,16 @@ const MutationMethods = {
768
1087
  constraint.constraintId,
769
1088
  ),
770
1089
  );
1090
+ uniqueItemMeta.push({
1091
+ role: "unique_delete",
1092
+ constraintField: fieldName,
1093
+ hasExistsGuard: false,
1094
+ });
771
1095
  }
772
1096
 
773
1097
  // Add new constraint unless value is null (clearing field removes constraint)
774
1098
  if (dyNewValue !== null) {
775
- transactItems.push(
1099
+ uniqueTransactItems.push(
776
1100
  await this._createUniqueConstraint(
777
1101
  fieldName,
778
1102
  dyNewValue,
@@ -780,6 +1104,11 @@ const MutationMethods = {
780
1104
  constraint.constraintId,
781
1105
  ),
782
1106
  );
1107
+ uniqueItemMeta.push({
1108
+ role: "unique_create",
1109
+ constraintField: fieldName,
1110
+ hasExistsGuard: false,
1111
+ });
783
1112
  }
784
1113
  } else if (dyNewValue !== undefined && currentItem) {
785
1114
  // Re-sending the unchanged value writes no constraint rows, so guard
@@ -855,7 +1184,6 @@ const MutationMethods = {
855
1184
  TableName: this.table,
856
1185
  Key: writeKey,
857
1186
  UpdateExpression: updateExpression,
858
- ReturnValues: "ALL_NEW",
859
1187
  };
860
1188
 
861
1189
  if (Object.keys(names).length > 0) {
@@ -956,14 +1284,58 @@ const MutationMethods = {
956
1284
  const dyKey = writeKey;
957
1285
  logger.debug("dyKey", dyKey);
958
1286
 
1287
+ return {
1288
+ primaryId,
1289
+ dyKey,
1290
+ dyUpdatesToSave,
1291
+ currentItem,
1292
+ consumedCapacity,
1293
+ hasUniqueConstraintChanges,
1294
+ uniqueTransactItems,
1295
+ uniqueItemMeta,
1296
+ updateParams,
1297
+ hasAtomicOps,
1298
+ existsGuard,
1299
+ };
1300
+ },
1301
+
1302
+ /**
1303
+ *@memberof BaoModel
1304
+ * @private
1305
+ * @description
1306
+ * Save an item to the database.
1307
+ * @param {string} primaryId - The primary ID of the item to save.
1308
+ * @param {Object} jsUpdates - The data to save the item with.
1309
+ * @param {Object} [options] - Additional options for the save operation.
1310
+ * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
1311
+ * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
1312
+ * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
1313
+ */
1314
+ async _saveItem(primaryId, jsUpdates, options = {}) {
1315
+ const { isNew = false } = options;
1316
+ const prepared = await this._prepareSave(primaryId, jsUpdates, options);
1317
+ const {
1318
+ dyKey,
1319
+ dyUpdatesToSave,
1320
+ currentItem,
1321
+ consumedCapacity,
1322
+ hasUniqueConstraintChanges,
1323
+ uniqueTransactItems,
1324
+ updateParams,
1325
+ hasAtomicOps,
1326
+ existsGuard,
1327
+ } = prepared;
1328
+ primaryId = prepared.primaryId;
1329
+
959
1330
  try {
960
1331
  let response;
961
1332
 
962
1333
  if (hasUniqueConstraintChanges) {
963
1334
  // Use transaction if we have unique constraint changes
964
- transactItems.push({
965
- Update: updateParams,
966
- });
1335
+ const transactItems = [
1336
+ ...uniqueTransactItems,
1337
+ { Update: updateParams },
1338
+ ];
967
1339
 
968
1340
  if (logger.isDebugEnabled()) {
969
1341
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
@@ -995,21 +1367,12 @@ const MutationMethods = {
995
1367
  // loader cache, which still holds the pre-update row.
996
1368
  let savedItem;
997
1369
  if (isNew || !hasAtomicOps) {
998
- const base = isNew
999
- ? {}
1000
- : currentItem.isLoaded()
1001
- ? currentItem._loadedDyData
1002
- : currentItem._dyData;
1003
- const storedItem = { ...base, ...dyKey };
1004
- for (const [key, value] of Object.entries(dyUpdatesToSave)) {
1005
- if (value === undefined) continue;
1006
- if (value === null) {
1007
- delete storedItem[key];
1008
- } else {
1009
- storedItem[key] = value;
1010
- }
1011
- }
1012
- savedItem = this._createFromDyItem(storedItem);
1370
+ savedItem = this._buildLocalSavedItem(
1371
+ isNew,
1372
+ currentItem,
1373
+ dyKey,
1374
+ dyUpdatesToSave,
1375
+ );
1013
1376
  } else {
1014
1377
  const readOptions = { batchDelay: 0, bypassCache: true };
1015
1378
  savedItem = await this.find(primaryId, readOptions);
@@ -1052,6 +1415,7 @@ const MutationMethods = {
1052
1415
  this.documentClient.send(
1053
1416
  new UpdateCommand({
1054
1417
  ...updateParams,
1418
+ ReturnValues: "ALL_NEW",
1055
1419
  ReturnConsumedCapacity: "TOTAL",
1056
1420
  }),
1057
1421
  );