dynamo-bao 0.1.5 → 0.1.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -64,6 +64,13 @@ class FilterExpressionBuilder {
64
64
  }
65
65
  const valueKeys = convertedValue.map((v) => this.generateValue(v));
66
66
  return `${nameKey} IN (${valueKeys.join(", ")})`;
67
+ case "$exists":
68
+ if (typeof value !== "boolean") {
69
+ throw new Error("$exists operator requires a boolean value");
70
+ }
71
+ return value
72
+ ? `attribute_exists(${nameKey})`
73
+ : `attribute_not_exists(${nameKey})`;
67
74
  default:
68
75
  throw new Error(`Unsupported operator: ${operator}`);
69
76
  }
@@ -225,6 +232,7 @@ class FilterExpressionBuilder {
225
232
  "$in",
226
233
  "$contains",
227
234
  "$beginsWith",
235
+ "$exists",
228
236
  ].includes(op)
229
237
  ) {
230
238
  throw new Error(`Invalid operator ${op} for field ${key}`);
@@ -1,11 +1,13 @@
1
1
  const {
2
2
  TransactWriteCommand,
3
3
  UpdateCommand,
4
+ DeleteCommand,
4
5
  } = require("@aws-sdk/lib-dynamodb");
5
6
  const { defaultLogger: logger } = require("../utils/logger");
6
7
  const { pluginManager } = require("../plugin-manager");
7
8
  const { retryOperation } = require("../utils/retry-helper");
8
9
  const assert = require("assert");
10
+ const { FilterExpressionBuilder } = require("../filter-expression");
9
11
 
10
12
  const MutationMethods = {
11
13
  /**
@@ -35,13 +37,23 @@ const MutationMethods = {
35
37
  * @param {string} primaryId - The primary ID of the item to update.
36
38
  * @param {Object} jsUpdates - The data to update the item with.
37
39
  * @param {Object} [options] - Additional options for the update operation.
40
+ * @param {Object} [options.condition] - Condition that must be met for the update to succeed.
41
+ * The condition supports the same operators as filter expressions:
42
+ * - Simple field comparisons: { fieldName: value } for exact matches
43
+ * - Comparison operators: { fieldName: { $eq: value, $ne: value, $gt: value, $gte: value, $lt: value, $lte: value } }
44
+ * - String operators: { fieldName: { $beginsWith: value, $contains: value } }
45
+ * - Existence check: { fieldName: { $exists: true|false } }
46
+ * - Logical operators: $and, $or, $not
38
47
  * @returns {Promise<Object>} Returns a promise that resolves to the updated item.
48
+ * @throws {Error} "Item not found" if the item doesn't exist
49
+ * @throws {Error} "Condition check failed" if the condition isn't satisfied
39
50
  */
40
51
  async update(primaryId, jsUpdates, options = {}) {
41
52
  const updateOptions = {
42
53
  isNew: false,
43
54
  ...options,
44
55
  };
56
+
45
57
  await pluginManager.executeHooks(
46
58
  this.name,
47
59
  "beforeSave",
@@ -69,6 +81,30 @@ const MutationMethods = {
69
81
  * Delete an existing item in the database.
70
82
  * @param {string} primaryId - The primary ID of the item to delete.
71
83
  * @param {Object} [options] - Additional options for the delete operation.
84
+ * @param {Object} [options.condition] - Condition that must be met for the delete to succeed.
85
+ * The condition supports the same operators as filter expressions:
86
+ * - Simple field comparisons: { fieldName: value } for exact matches
87
+ * - Comparison operators: { fieldName: { $eq: value, $ne: value, $gt: value, $gte: value, $lt: value, $lte: value } }
88
+ * - String operators: { fieldName: { $beginsWith: value, $contains: value } }
89
+ * - Existence check: { fieldName: { $exists: true|false } }
90
+ * - Logical operators: $and, $or, $not
91
+ * @example
92
+ * // Delete with simple condition
93
+ * await Model.delete(id, {
94
+ * condition: { status: 'active' }
95
+ * });
96
+ *
97
+ * // Delete with complex condition
98
+ * await Model.delete(id, {
99
+ * condition: {
100
+ * $and: [
101
+ * { status: { $exists: true } },
102
+ * { age: { $gt: 21 } }
103
+ * ]
104
+ * }
105
+ * });
106
+ * @throws {Error} "Item not found" if the item doesn't exist
107
+ * @throws {Error} "Delete condition not met" if the condition isn't satisfied
72
108
  * @returns {Promise<Object>} Returns a promise that resolves to the deleted item.
73
109
  */
74
110
  async delete(primaryId, options = {}) {
@@ -84,54 +120,129 @@ const MutationMethods = {
84
120
  throw new Error("Item not found");
85
121
  }
86
122
 
87
- const transactItems = [
88
- {
89
- Delete: {
123
+ // Check if we need to clean up any unique constraints
124
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
125
+ const hasConstraintsToClean = uniqueConstraints.some((constraint) => {
126
+ const value = item[constraint.field];
127
+ return value != null;
128
+ });
129
+
130
+ try {
131
+ let response;
132
+
133
+ if (hasConstraintsToClean) {
134
+ // Transaction path - handle unique constraint cleanup
135
+ const transactItems = [
136
+ {
137
+ Delete: {
138
+ TableName: this.table,
139
+ Key: {
140
+ _pk: item._dyData._pk,
141
+ _sk: item._dyData._sk,
142
+ },
143
+ },
144
+ },
145
+ ];
146
+
147
+ // Add condition if specified
148
+ if (options.condition) {
149
+ const builder = new FilterExpressionBuilder();
150
+ const filterExpression = builder.build(options.condition, this);
151
+
152
+ if (filterExpression) {
153
+ transactItems[0].Delete = {
154
+ ...transactItems[0].Delete,
155
+ ConditionExpression: filterExpression.FilterExpression,
156
+ ExpressionAttributeNames:
157
+ filterExpression.ExpressionAttributeNames,
158
+ ExpressionAttributeValues:
159
+ filterExpression.ExpressionAttributeValues,
160
+ };
161
+ }
162
+ }
163
+
164
+ // Add unique constraint cleanup operations
165
+ for (const constraint of uniqueConstraints) {
166
+ const value = item[constraint.field];
167
+ if (value) {
168
+ const constraintOp = await this._removeUniqueConstraint(
169
+ constraint.field,
170
+ value,
171
+ item.getPrimaryId(),
172
+ constraint.constraintId,
173
+ );
174
+ transactItems.push(constraintOp);
175
+ }
176
+ }
177
+
178
+ response = await retryOperation(() =>
179
+ this.documentClient.send(
180
+ new TransactWriteCommand({
181
+ TransactItems: transactItems,
182
+ ReturnConsumedCapacity: "TOTAL",
183
+ }),
184
+ ),
185
+ );
186
+ } else {
187
+ // Fast path - simple delete
188
+ const deleteParams = {
90
189
  TableName: this.table,
91
190
  Key: {
92
191
  _pk: item._dyData._pk,
93
192
  _sk: item._dyData._sk,
94
193
  },
95
- },
96
- },
97
- ];
194
+ ReturnValues: "ALL_OLD",
195
+ ReturnConsumedCapacity: "TOTAL",
196
+ };
98
197
 
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);
198
+ // Add condition if specified
199
+ if (options.condition) {
200
+ const builder = new FilterExpressionBuilder();
201
+ const filterExpression = builder.build(options.condition, this);
202
+
203
+ if (filterExpression) {
204
+ deleteParams.ConditionExpression =
205
+ filterExpression.FilterExpression;
206
+ deleteParams.ExpressionAttributeNames =
207
+ filterExpression.ExpressionAttributeNames;
208
+ deleteParams.ExpressionAttributeValues =
209
+ filterExpression.ExpressionAttributeValues;
210
+ }
112
211
  }
113
- }
114
- }
115
212
 
116
- const response = await retryOperation(() =>
117
- this.documentClient.send(
118
- new TransactWriteCommand({
119
- TransactItems: transactItems,
120
- ReturnConsumedCapacity: "TOTAL",
121
- }),
122
- ),
123
- );
213
+ response = await retryOperation(() =>
214
+ this.documentClient.send(new DeleteCommand(deleteParams)),
215
+ );
216
+ }
124
217
 
125
- await pluginManager.executeHooks(
126
- this.name,
127
- "afterDelete",
128
- primaryId,
129
- options,
130
- );
218
+ await pluginManager.executeHooks(
219
+ this.name,
220
+ "afterDelete",
221
+ primaryId,
222
+ options,
223
+ );
131
224
 
132
- // Return deleted item info with capacity information
133
- item._setConsumedCapacity(response.ConsumedCapacity, "write", false);
134
- return item;
225
+ // For transaction path, we already have the item
226
+ // For fast path, we get it from the response
227
+ const deletedItem = hasConstraintsToClean
228
+ ? item
229
+ : this._createFromDyItem(response.Attributes);
230
+ deletedItem._setConsumedCapacity(
231
+ response.ConsumedCapacity,
232
+ "write",
233
+ false,
234
+ );
235
+ return deletedItem;
236
+ } catch (error) {
237
+ if (
238
+ error.name === "ConditionalCheckFailedException" ||
239
+ (error.name === "TransactionCanceledException" &&
240
+ error.CancellationReasons?.[0]?.Code === "ConditionalCheckFailed")
241
+ ) {
242
+ throw new Error("Delete condition not met");
243
+ }
244
+ throw error;
245
+ }
135
246
  },
136
247
 
137
248
  _createNewPrimaryId(jsUpdates) {
@@ -160,17 +271,11 @@ const MutationMethods = {
160
271
  * @param {Object} [options] - Additional options for the save operation.
161
272
  * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
162
273
  * @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
274
  * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
170
275
  */
171
276
  async _saveItem(primaryId, jsUpdates, options = {}) {
172
277
  try {
173
- const { isNew = false, instanceObj = null, constraints = {} } = options;
278
+ const { isNew = false, instanceObj = null } = options;
174
279
 
175
280
  logger.debug("saveItem", primaryId, isNew, instanceObj);
176
281
  let consumedCapacity = [];
@@ -180,10 +285,14 @@ const MutationMethods = {
180
285
  currentItem = null;
181
286
  } else if (!currentItem) {
182
287
  currentItem = await this.find(primaryId, { batchDelay: 0 });
183
- consumedCapacity = [
184
- ...consumedCapacity,
185
- ...currentItem.getConsumedCapacity(),
186
- ];
288
+ if (currentItem && currentItem.exists()) {
289
+ consumedCapacity = [
290
+ ...consumedCapacity,
291
+ ...currentItem.getConsumedCapacity(),
292
+ ];
293
+ } else {
294
+ throw new Error("Item not found");
295
+ }
187
296
  }
188
297
 
189
298
  if (!isNew && !currentItem) {
@@ -297,66 +406,17 @@ const MutationMethods = {
297
406
  logger.debug("indexKeys", indexKeys);
298
407
  Object.assign(dyUpdatesToSave, indexKeys);
299
408
 
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
409
+ // Build the update expression first
346
410
  const { updateExpression, names, values } =
347
411
  this._buildUpdateExpression(dyUpdatesToSave);
348
412
 
349
- const dyKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
350
- logger.debug("dyKey", dyKey);
351
-
352
- // Create the update params
413
+ // Create the base update params
353
414
  const updateParams = {
354
415
  TableName: this.table,
355
- Key: dyKey,
416
+ Key: this._getDyKeyForPkSk(this._parsePrimaryId(primaryId)),
356
417
  UpdateExpression: updateExpression,
357
418
  ExpressionAttributeNames: {
358
419
  ...names,
359
- ...conditionNames,
360
420
  },
361
421
  ReturnValues: "ALL_NEW",
362
422
  };
@@ -364,19 +424,41 @@ const MutationMethods = {
364
424
  if (Object.keys(values).length > 0) {
365
425
  updateParams.ExpressionAttributeValues = {
366
426
  ...values,
367
- ...conditionValues,
368
427
  };
369
428
  }
370
429
 
371
- // Add condition expression if we have any conditions
372
- if (conditionExpressions.length > 0) {
373
- updateParams.ConditionExpression = conditionExpressions.join(" AND ");
430
+ // Build the condition expression for the update/put
431
+ const conditionExpressions = [];
432
+ const conditionNames = {};
433
+ const conditionValues = {};
434
+
435
+ if (options.condition) {
436
+ const builder = new FilterExpressionBuilder();
437
+ const filterExpression = builder.build(options.condition, this);
438
+
439
+ if (filterExpression) {
440
+ updateParams.ConditionExpression = filterExpression.FilterExpression;
441
+ updateParams.ExpressionAttributeNames = {
442
+ ...updateParams.ExpressionAttributeNames,
443
+ ...filterExpression.ExpressionAttributeNames,
444
+ };
445
+ updateParams.ExpressionAttributeValues = {
446
+ ...updateParams.ExpressionAttributeValues,
447
+ ...filterExpression.ExpressionAttributeValues,
448
+ };
449
+ }
374
450
  } else if (isNew) {
375
- // Default condition for new items if no other conditions specified
451
+ // For new items, ensure they don't already exist
376
452
  updateParams.ConditionExpression = "attribute_not_exists(#pk)";
377
- updateParams.ExpressionAttributeNames["#pk"] = "_pk";
453
+ updateParams.ExpressionAttributeNames = {
454
+ ...updateParams.ExpressionAttributeNames,
455
+ "#pk": "_pk",
456
+ };
378
457
  }
379
458
 
459
+ const dyKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
460
+ logger.debug("dyKey", dyKey);
461
+
380
462
  try {
381
463
  let response;
382
464
 
@@ -451,15 +533,6 @@ const MutationMethods = {
451
533
  } catch (error) {
452
534
  logger.error("Error in _saveItem", error);
453
535
  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
536
  throw new Error("Condition check failed", error);
464
537
  }
465
538