dynamo-bao 0.1.5 → 0.1.7

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.
@@ -1,11 +1,18 @@
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");
11
+ const {
12
+ ItemNotFoundError,
13
+ ConditionalError,
14
+ ValidationError,
15
+ } = require("../exceptions");
9
16
 
10
17
  const MutationMethods = {
11
18
  /**
@@ -35,13 +42,23 @@ const MutationMethods = {
35
42
  * @param {string} primaryId - The primary ID of the item to update.
36
43
  * @param {Object} jsUpdates - The data to update the item with.
37
44
  * @param {Object} [options] - Additional options for the update operation.
45
+ * @param {Object} [options.condition] - Condition that must be met for the update to succeed.
46
+ * The condition supports the same operators as filter expressions:
47
+ * - Simple field comparisons: { fieldName: value } for exact matches
48
+ * - Comparison operators: { fieldName: { $eq: value, $ne: value, $gt: value, $gte: value, $lt: value, $lte: value } }
49
+ * - String operators: { fieldName: { $beginsWith: value, $contains: value } }
50
+ * - Existence check: { fieldName: { $exists: true|false } }
51
+ * - Logical operators: $and, $or, $not
38
52
  * @returns {Promise<Object>} Returns a promise that resolves to the updated item.
53
+ * @throws {Error} "Item not found" if the item doesn't exist
54
+ * @throws {Error} "Condition check failed" if the condition isn't satisfied
39
55
  */
40
56
  async update(primaryId, jsUpdates, options = {}) {
41
57
  const updateOptions = {
42
58
  isNew: false,
43
59
  ...options,
44
60
  };
61
+
45
62
  await pluginManager.executeHooks(
46
63
  this.name,
47
64
  "beforeSave",
@@ -69,6 +86,30 @@ const MutationMethods = {
69
86
  * Delete an existing item in the database.
70
87
  * @param {string} primaryId - The primary ID of the item to delete.
71
88
  * @param {Object} [options] - Additional options for the delete operation.
89
+ * @param {Object} [options.condition] - Condition that must be met for the delete to succeed.
90
+ * The condition supports the same operators as filter expressions:
91
+ * - Simple field comparisons: { fieldName: value } for exact matches
92
+ * - Comparison operators: { fieldName: { $eq: value, $ne: value, $gt: value, $gte: value, $lt: value, $lte: value } }
93
+ * - String operators: { fieldName: { $beginsWith: value, $contains: value } }
94
+ * - Existence check: { fieldName: { $exists: true|false } }
95
+ * - Logical operators: $and, $or, $not
96
+ * @example
97
+ * // Delete with simple condition
98
+ * await Model.delete(id, {
99
+ * condition: { status: 'active' }
100
+ * });
101
+ *
102
+ * // Delete with complex condition
103
+ * await Model.delete(id, {
104
+ * condition: {
105
+ * $and: [
106
+ * { status: { $exists: true } },
107
+ * { age: { $gt: 21 } }
108
+ * ]
109
+ * }
110
+ * });
111
+ * @throws {Error} "Item not found" if the item doesn't exist
112
+ * @throws {Error} "Delete condition not met" if the condition isn't satisfied
72
113
  * @returns {Promise<Object>} Returns a promise that resolves to the deleted item.
73
114
  */
74
115
  async delete(primaryId, options = {}) {
@@ -81,57 +122,137 @@ const MutationMethods = {
81
122
 
82
123
  const item = await this.find(primaryId, { batchDelay: 0 });
83
124
  if (!item) {
84
- throw new Error("Item not found");
125
+ throw new ItemNotFoundError("Item not found", primaryId);
85
126
  }
86
127
 
87
- const transactItems = [
88
- {
89
- Delete: {
128
+ // Check if we need to clean up any unique constraints
129
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
130
+ const hasConstraintsToClean = uniqueConstraints.some((constraint) => {
131
+ const value = item[constraint.field];
132
+ return value != null;
133
+ });
134
+
135
+ try {
136
+ let response;
137
+
138
+ if (hasConstraintsToClean) {
139
+ // Transaction path - handle unique constraint cleanup
140
+ const transactItems = [
141
+ {
142
+ Delete: {
143
+ TableName: this.table,
144
+ Key: {
145
+ _pk: item._dyData._pk,
146
+ _sk: item._dyData._sk,
147
+ },
148
+ },
149
+ },
150
+ ];
151
+
152
+ // Add condition if specified
153
+ if (options.condition) {
154
+ const builder = new FilterExpressionBuilder();
155
+ const filterExpression = builder.build(options.condition, this);
156
+
157
+ if (filterExpression) {
158
+ transactItems[0].Delete = {
159
+ ...transactItems[0].Delete,
160
+ ConditionExpression: filterExpression.FilterExpression,
161
+ ExpressionAttributeNames:
162
+ filterExpression.ExpressionAttributeNames,
163
+ ExpressionAttributeValues:
164
+ filterExpression.ExpressionAttributeValues,
165
+ };
166
+ }
167
+ }
168
+
169
+ // Add unique constraint cleanup operations
170
+ for (const constraint of uniqueConstraints) {
171
+ const value = item[constraint.field];
172
+ if (value) {
173
+ const constraintOp = await this._removeUniqueConstraint(
174
+ constraint.field,
175
+ value,
176
+ item.getPrimaryId(),
177
+ constraint.constraintId,
178
+ );
179
+ transactItems.push(constraintOp);
180
+ }
181
+ }
182
+
183
+ response = await retryOperation(() =>
184
+ this.documentClient.send(
185
+ new TransactWriteCommand({
186
+ TransactItems: transactItems,
187
+ ReturnConsumedCapacity: "TOTAL",
188
+ }),
189
+ ),
190
+ );
191
+ } else {
192
+ // Fast path - simple delete
193
+ const deleteParams = {
90
194
  TableName: this.table,
91
195
  Key: {
92
196
  _pk: item._dyData._pk,
93
197
  _sk: item._dyData._sk,
94
198
  },
95
- },
96
- },
97
- ];
199
+ ReturnValues: "ALL_OLD",
200
+ ReturnConsumedCapacity: "TOTAL",
201
+ };
98
202
 
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);
203
+ // Add condition if specified
204
+ if (options.condition) {
205
+ const builder = new FilterExpressionBuilder();
206
+ const filterExpression = builder.build(options.condition, this);
207
+
208
+ if (filterExpression) {
209
+ deleteParams.ConditionExpression =
210
+ filterExpression.FilterExpression;
211
+ deleteParams.ExpressionAttributeNames =
212
+ filterExpression.ExpressionAttributeNames;
213
+ deleteParams.ExpressionAttributeValues =
214
+ filterExpression.ExpressionAttributeValues;
215
+ }
112
216
  }
217
+
218
+ response = await retryOperation(() =>
219
+ this.documentClient.send(new DeleteCommand(deleteParams)),
220
+ );
113
221
  }
114
- }
115
222
 
116
- const response = await retryOperation(() =>
117
- this.documentClient.send(
118
- new TransactWriteCommand({
119
- TransactItems: transactItems,
120
- ReturnConsumedCapacity: "TOTAL",
121
- }),
122
- ),
123
- );
223
+ await pluginManager.executeHooks(
224
+ this.name,
225
+ "afterDelete",
226
+ primaryId,
227
+ options,
228
+ );
124
229
 
125
- await pluginManager.executeHooks(
126
- this.name,
127
- "afterDelete",
128
- primaryId,
129
- options,
130
- );
230
+ // For transaction path, we already have the item
231
+ // For fast path, we get it from the response
232
+ const deletedItem = hasConstraintsToClean
233
+ ? item
234
+ : this._createFromDyItem(response.Attributes);
235
+ deletedItem._setConsumedCapacity(
236
+ response.ConsumedCapacity,
237
+ "write",
238
+ false,
239
+ );
131
240
 
132
- // Return deleted item info with capacity information
133
- item._setConsumedCapacity(response.ConsumedCapacity, "write", false);
134
- return item;
241
+ return deletedItem;
242
+ } catch (error) {
243
+ if (
244
+ error.name === "ConditionalCheckFailedException" ||
245
+ (error.name === "TransactionCanceledException" &&
246
+ error.CancellationReasons?.[0]?.Code === "ConditionalCheckFailed")
247
+ ) {
248
+ throw new ConditionalError(
249
+ "Delete condition not met",
250
+ "delete",
251
+ options.condition,
252
+ );
253
+ }
254
+ throw error;
255
+ }
135
256
  },
136
257
 
137
258
  _createNewPrimaryId(jsUpdates) {
@@ -160,17 +281,11 @@ const MutationMethods = {
160
281
  * @param {Object} [options] - Additional options for the save operation.
161
282
  * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
162
283
  * @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
284
  * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
170
285
  */
171
286
  async _saveItem(primaryId, jsUpdates, options = {}) {
172
287
  try {
173
- const { isNew = false, instanceObj = null, constraints = {} } = options;
288
+ const { isNew = false, instanceObj = null } = options;
174
289
 
175
290
  logger.debug("saveItem", primaryId, isNew, instanceObj);
176
291
  let consumedCapacity = [];
@@ -180,14 +295,18 @@ const MutationMethods = {
180
295
  currentItem = null;
181
296
  } else if (!currentItem) {
182
297
  currentItem = await this.find(primaryId, { batchDelay: 0 });
183
- consumedCapacity = [
184
- ...consumedCapacity,
185
- ...currentItem.getConsumedCapacity(),
186
- ];
298
+ if (currentItem && currentItem.exists()) {
299
+ consumedCapacity = [
300
+ ...consumedCapacity,
301
+ ...currentItem.getConsumedCapacity(),
302
+ ];
303
+ } else {
304
+ throw new ItemNotFoundError("Item not found", primaryId);
305
+ }
187
306
  }
188
307
 
189
308
  if (!isNew && !currentItem) {
190
- throw new Error("Item not found");
309
+ throw new ItemNotFoundError("Item not found", primaryId);
191
310
  }
192
311
 
193
312
  const transactItems = [];
@@ -229,7 +348,11 @@ const MutationMethods = {
229
348
  (jsUpdates[fieldName] === undefined ||
230
349
  jsUpdates[fieldName] === null)
231
350
  ) {
232
- throw new Error(`Field is required: ${fieldName} `);
351
+ throw new ValidationError(
352
+ `Field is required: ${fieldName}`,
353
+ fieldName,
354
+ jsUpdates[fieldName],
355
+ );
233
356
  }
234
357
  }
235
358
  }
@@ -297,66 +420,17 @@ const MutationMethods = {
297
420
  logger.debug("indexKeys", indexKeys);
298
421
  Object.assign(dyUpdatesToSave, indexKeys);
299
422
 
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
423
+ // Build the update expression first
346
424
  const { updateExpression, names, values } =
347
425
  this._buildUpdateExpression(dyUpdatesToSave);
348
426
 
349
- const dyKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
350
- logger.debug("dyKey", dyKey);
351
-
352
- // Create the update params
427
+ // Create the base update params
353
428
  const updateParams = {
354
429
  TableName: this.table,
355
- Key: dyKey,
430
+ Key: this._getDyKeyForPkSk(this._parsePrimaryId(primaryId)),
356
431
  UpdateExpression: updateExpression,
357
432
  ExpressionAttributeNames: {
358
433
  ...names,
359
- ...conditionNames,
360
434
  },
361
435
  ReturnValues: "ALL_NEW",
362
436
  };
@@ -364,19 +438,41 @@ const MutationMethods = {
364
438
  if (Object.keys(values).length > 0) {
365
439
  updateParams.ExpressionAttributeValues = {
366
440
  ...values,
367
- ...conditionValues,
368
441
  };
369
442
  }
370
443
 
371
- // Add condition expression if we have any conditions
372
- if (conditionExpressions.length > 0) {
373
- updateParams.ConditionExpression = conditionExpressions.join(" AND ");
444
+ // Build the condition expression for the update/put
445
+ const conditionExpressions = [];
446
+ const conditionNames = {};
447
+ const conditionValues = {};
448
+
449
+ if (options.condition) {
450
+ const builder = new FilterExpressionBuilder();
451
+ const filterExpression = builder.build(options.condition, this);
452
+
453
+ if (filterExpression) {
454
+ updateParams.ConditionExpression = filterExpression.FilterExpression;
455
+ updateParams.ExpressionAttributeNames = {
456
+ ...updateParams.ExpressionAttributeNames,
457
+ ...filterExpression.ExpressionAttributeNames,
458
+ };
459
+ updateParams.ExpressionAttributeValues = {
460
+ ...updateParams.ExpressionAttributeValues,
461
+ ...filterExpression.ExpressionAttributeValues,
462
+ };
463
+ }
374
464
  } else if (isNew) {
375
- // Default condition for new items if no other conditions specified
465
+ // For new items, ensure they don't already exist
376
466
  updateParams.ConditionExpression = "attribute_not_exists(#pk)";
377
- updateParams.ExpressionAttributeNames["#pk"] = "_pk";
467
+ updateParams.ExpressionAttributeNames = {
468
+ ...updateParams.ExpressionAttributeNames,
469
+ "#pk": "_pk",
470
+ };
378
471
  }
379
472
 
473
+ const dyKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
474
+ logger.debug("dyKey", dyKey);
475
+
380
476
  try {
381
477
  let response;
382
478
 
@@ -407,7 +503,7 @@ const MutationMethods = {
407
503
  logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
408
504
 
409
505
  if (!savedItem.exists()) {
410
- throw new Error("Failed to fetch saved item");
506
+ throw new ConditionalError("Failed to fetch saved item", "update");
411
507
  }
412
508
 
413
509
  // Set the consumed capacity from the transaction
@@ -446,24 +542,34 @@ const MutationMethods = {
446
542
  false,
447
543
  );
448
544
  savedItem._addConsumedCapacity(consumedCapacity, "read", false);
545
+
546
+ if (!savedItem.exists()) {
547
+ throw new ConditionalError("Failed to fetch saved item", "update");
548
+ }
549
+
449
550
  return savedItem;
450
551
  }
451
552
  } catch (error) {
452
553
  logger.error("Error in _saveItem", error);
453
554
  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);
555
+ throw new ConditionalError("Condition check failed", "update", error);
464
556
  }
465
557
 
466
558
  if (error.name === "TransactionCanceledException") {
559
+ // Check if it's due to conditional check failure
560
+ if (
561
+ error.CancellationReasons?.some(
562
+ (reason) => reason.Code === "ConditionalCheckFailed",
563
+ )
564
+ ) {
565
+ throw new ConditionalError(
566
+ "Transaction cancelled due to condition check failure",
567
+ "update",
568
+ error,
569
+ );
570
+ }
571
+ // For other transaction cancellation reasons, try to validate unique constraints
572
+ // which will throw the appropriate ConditionalError if that's the issue
467
573
  await this._validateUniqueConstraints(
468
574
  jsUpdates,
469
575
  isNew ? null : primaryId,
@@ -6,6 +6,7 @@ const { PrimaryKeyConfig } = require("../model-config");
6
6
  const assert = require("assert");
7
7
  const { retryOperation } = require("../utils/retry-helper");
8
8
  const { QueryCommand } = require("@aws-sdk/lib-dynamodb");
9
+ const { QueryError } = require("../exceptions");
9
10
 
10
11
  const QueryMethods = {
11
12
  /**
@@ -139,15 +140,20 @@ const QueryMethods = {
139
140
  async queryByIndex(indexName, pkValue, skCondition = null, options = {}) {
140
141
  const index = this.indexes[indexName];
141
142
  if (!index) {
142
- throw new Error(`Index "${indexName}" not found in ${this.name} model`);
143
+ throw new QueryError(
144
+ `Index "${indexName}" not found in ${this.name} model`,
145
+ indexName,
146
+ );
143
147
  }
144
148
 
145
149
  // Validate sort key field if condition is provided
146
150
  if (skCondition) {
147
151
  const [[fieldName]] = Object.entries(skCondition);
148
152
  if (fieldName !== index.sk) {
149
- throw new Error(
153
+ throw new QueryError(
150
154
  `Field "${fieldName}" is not the sort key for index "${indexName}"`,
155
+ indexName,
156
+ fieldName,
151
157
  );
152
158
  }
153
159
  }
@@ -1,6 +1,7 @@
1
1
  const { GetCommand } = require("@aws-sdk/lib-dynamodb");
2
2
  const { defaultLogger: logger } = require("../utils/logger");
3
3
  const { UNIQUE_CONSTRAINT_KEY } = require("../constants");
4
+ const { ConditionalError } = require("../exceptions");
4
5
 
5
6
  const UniqueConstraintMethods = {
6
7
  async _validateUniqueConstraints(data, currentId = null) {
@@ -51,15 +52,23 @@ const UniqueConstraintMethods = {
51
52
  if (result.Item) {
52
53
  logger.debug("Found existing constraint:", result.Item);
53
54
  if (!currentId || result.Item.relatedId !== currentId) {
54
- throw new Error(`${constraint.field} must be unique`);
55
+ throw new ConditionalError(
56
+ `${constraint.field} must be unique`,
57
+ "unique_constraint",
58
+ constraint.field,
59
+ );
55
60
  }
56
61
  }
57
62
  } catch (innerError) {
58
- if (innerError.message.includes("must be unique")) {
63
+ if (innerError instanceof ConditionalError) {
59
64
  throw innerError;
60
65
  }
61
66
  console.error("Error checking unique constraint:", innerError);
62
- throw new Error(`Failed to validate ${constraint.field} uniqueness`);
67
+ throw new ConditionalError(
68
+ `Failed to validate ${constraint.field} uniqueness`,
69
+ "unique_constraint",
70
+ constraint.field,
71
+ );
63
72
  }
64
73
  }
65
74
  },
@@ -1,6 +1,7 @@
1
1
  const { defaultLogger: logger } = require("../utils/logger");
2
2
  const { TtlFieldClass } = require("../fields");
3
3
  const { PrimaryKeyConfig } = require("../model-config");
4
+ const { ConfigurationError } = require("../exceptions");
4
5
  const {
5
6
  GSI_INDEX_ID1,
6
7
  GSI_INDEX_ID2,
@@ -43,18 +44,25 @@ const ValidationMethods = {
43
44
  */
44
45
  _validateConfiguration() {
45
46
  if (!this.modelPrefix) {
46
- throw new Error(`${this.name} must define a modelPrefix`);
47
+ throw new ConfigurationError(
48
+ `${this.name} must define a modelPrefix`,
49
+ this.name,
50
+ );
47
51
  }
48
52
 
49
53
  if (!this.primaryKey) {
50
- throw new Error(`${this.name} must define a primaryKey`);
54
+ throw new ConfigurationError(
55
+ `${this.name} must define a primaryKey`,
56
+ this.name,
57
+ );
51
58
  }
52
59
 
53
60
  // Update to use TtlFieldClass instead of TtlField
54
61
  Object.entries(this.fields).forEach(([fieldName, field]) => {
55
62
  if (field instanceof TtlFieldClass && fieldName !== "ttl") {
56
- throw new Error(
63
+ throw new ConfigurationError(
57
64
  `TtlField must be named 'ttl', found '${fieldName}' in ${this.name}`,
65
+ this.name,
58
66
  );
59
67
  }
60
68
  });
@@ -79,8 +87,9 @@ const ValidationMethods = {
79
87
  // Validate field names don't start with underscore
80
88
  Object.keys(this.fields).forEach((fieldName) => {
81
89
  if (fieldName.startsWith("_")) {
82
- throw new Error(
90
+ throw new ConfigurationError(
83
91
  `Field name '${fieldName}' in ${this.name} cannot start with underscore`,
92
+ this.name,
84
93
  );
85
94
  }
86
95
  });
@@ -96,20 +105,23 @@ const ValidationMethods = {
96
105
  Object.entries(this.indexes).forEach(([indexName, index]) => {
97
106
  // Check if index name starts with underscore
98
107
  if (indexName.startsWith("_")) {
99
- throw new Error(
108
+ throw new ConfigurationError(
100
109
  `Index name '${indexName}' in ${this.name} cannot start with underscore`,
110
+ this.name,
101
111
  );
102
112
  }
103
113
 
104
114
  // Check if referenced fields start with underscore
105
115
  if (index.pk !== "modelPrefix" && index.pk.startsWith("_")) {
106
- throw new Error(
116
+ throw new ConfigurationError(
107
117
  `Index '${indexName}' references invalid field '${index.pk}' (cannot start with underscore)`,
118
+ this.name,
108
119
  );
109
120
  }
110
121
  if (index.sk !== "modelPrefix" && index.sk.startsWith("_")) {
111
- throw new Error(
122
+ throw new ConfigurationError(
112
123
  `Index '${indexName}' references invalid field '${index.sk}' (cannot start with underscore)`,
124
+ this.name,
113
125
  );
114
126
  }
115
127
 
@@ -120,7 +132,10 @@ const ValidationMethods = {
120
132
  index.sk === this.primaryKey.sk;
121
133
 
122
134
  if (!validIndexIds.includes(index.indexId) && !isPrimaryKeyIndex) {
123
- throw new Error(`Invalid index ID ${index.indexId} in ${this.name}`);
135
+ throw new ConfigurationError(
136
+ `Invalid index ID ${index.indexId} in ${this.name}`,
137
+ this.name,
138
+ );
124
139
  }
125
140
 
126
141
  // These will throw errors if the fields don't exist
@@ -137,14 +152,16 @@ const ValidationMethods = {
137
152
 
138
153
  Object.values(this.uniqueConstraints || {}).forEach((constraint) => {
139
154
  if (!validConstraintIds.includes(constraint.constraintId)) {
140
- throw new Error(
155
+ throw new ConfigurationError(
141
156
  `Invalid constraint ID ${constraint.constraintId} in ${this.name}`,
157
+ this.name,
142
158
  );
143
159
  }
144
160
 
145
161
  if (!this._getField(constraint.field)) {
146
- throw new Error(
162
+ throw new ConfigurationError(
147
163
  `Unique constraint field '${constraint.field}' not found in ${this.name} fields`,
164
+ this.name,
148
165
  );
149
166
  }
150
167
  });
@@ -2,6 +2,7 @@ const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
2
2
  const { DynamoDBDocument } = require("@aws-sdk/lib-dynamodb");
3
3
  const { defaultLogger: logger } = require("./utils/logger");
4
4
  const { pluginManager } = require("./plugin-manager");
5
+ const { ConfigurationError } = require("./exceptions");
5
6
 
6
7
  class ModelManager {
7
8
  static _instances = new Map();
@@ -45,11 +46,11 @@ class ModelManager {
45
46
  }
46
47
 
47
48
  getModel(modelName) {
48
- const ModelClass = this._models.get(modelName);
49
- if (!ModelClass) {
50
- throw new Error(`Model ${modelName} not found`);
49
+ const model = this._models.get(modelName);
50
+ if (!model) {
51
+ throw new ConfigurationError(`Model ${modelName} not found`);
51
52
  }
52
- return ModelClass;
53
+ return model;
53
54
  }
54
55
 
55
56
  // Registry methods