dynamo-bao 0.1.6 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -45,7 +45,8 @@
45
45
  "jest": "^29.7.0",
46
46
  "jsdoc": "^4.0.4",
47
47
  "prettier": "3.4.2",
48
- "serverless": "^3.38.0"
48
+ "serverless": "^3.38.0",
49
+ "formidable": ">=2.1.3"
49
50
  },
50
51
  "bin": {
51
52
  "bao-init": "bin/dynamo-bao-create-table.js",
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @fileoverview
3
+ * Custom exception classes for dynamo-bao library.
4
+ * These provide more specific error types than generic Error objects.
5
+ */
6
+
7
+ /**
8
+ * Base class for all dynamo-bao exceptions
9
+ */
10
+ class BaoError extends Error {
11
+ constructor(message, code = null) {
12
+ super(message);
13
+ this.name = this.constructor.name;
14
+ this.code = code;
15
+ Error.captureStackTrace(this, this.constructor);
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Thrown when model configuration is invalid
21
+ * Examples: missing modelPrefix, invalid field names, invalid index configurations
22
+ */
23
+ class ConfigurationError extends BaoError {
24
+ constructor(message, modelName = null) {
25
+ super(message);
26
+ this.modelName = modelName;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Thrown when field validation fails
32
+ * Examples: required field missing, invalid ULID format, type validation failures
33
+ */
34
+ class ValidationError extends BaoError {
35
+ constructor(message, fieldName = null, value = null) {
36
+ super(message);
37
+ this.fieldName = fieldName;
38
+ this.value = value;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Thrown when query construction or execution fails
44
+ * Examples: invalid operators, field not found, index not found, malformed conditions
45
+ */
46
+ class QueryError extends BaoError {
47
+ constructor(message, indexName = null, fieldName = null) {
48
+ super(message);
49
+ this.indexName = indexName;
50
+ this.fieldName = fieldName;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Thrown when a database item is not found
56
+ * This is distinct from the existing ObjectNotFound class which is a result wrapper
57
+ */
58
+ class ItemNotFoundError extends BaoError {
59
+ constructor(message = "Item not found", primaryId = null) {
60
+ super(message);
61
+ this.primaryId = primaryId;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Thrown when DynamoDB operations fail due to conditions
67
+ * Examples: conditional check failures, unique constraint violations
68
+ */
69
+ class ConditionalError extends BaoError {
70
+ constructor(message, operation = null, condition = null) {
71
+ super(message);
72
+ this.operation = operation;
73
+ this.condition = condition;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Thrown when data parsing or conversion fails
79
+ * Examples: invalid primary ID format, JSON parsing errors, type conversion failures
80
+ */
81
+ class DataFormatError extends BaoError {
82
+ constructor(message, data = null, expectedFormat = null) {
83
+ super(message);
84
+ this.data = data;
85
+ this.expectedFormat = expectedFormat;
86
+ }
87
+ }
88
+
89
+ module.exports = {
90
+ BaoError,
91
+ ConfigurationError,
92
+ ValidationError,
93
+ QueryError,
94
+ ItemNotFoundError,
95
+ ConditionalError,
96
+ DataFormatError,
97
+ };
package/src/fields.js CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  const { ulid, decodeTime } = require("ulid");
7
7
  const { defaultLogger: logger } = require("./utils/logger");
8
+ const { ValidationError } = require("./exceptions");
8
9
 
9
10
  /**
10
11
  * @class BaoBaseField
@@ -43,7 +44,7 @@ class BaoBaseField {
43
44
  */
44
45
  validate(value) {
45
46
  if (this.required && (value === null || value === undefined)) {
46
- throw new Error("Field is required");
47
+ throw new ValidationError("Field is required", null, value);
47
48
  }
48
49
  return true;
49
50
  }
@@ -155,7 +156,19 @@ class BaoBaseField {
155
156
  * A field that stores a string value.
156
157
  */
157
158
  class StringField extends BaoBaseField {
158
- // String fields are pass-through since DynamoDB handles them natively
159
+ validate(value) {
160
+ if (this.required && !value) {
161
+ throw new ValidationError("Field is required", null, value);
162
+ }
163
+ if (value && this.maxLength && value.length > this.maxLength) {
164
+ throw new ValidationError(
165
+ `Value exceeds maximum length of ${this.maxLength}`,
166
+ null,
167
+ value,
168
+ );
169
+ }
170
+ return true;
171
+ }
159
172
  }
160
173
 
161
174
  /**
@@ -167,7 +180,7 @@ class StringField extends BaoBaseField {
167
180
  class DateTimeField extends BaoBaseField {
168
181
  validate(value) {
169
182
  if (this.required && value === undefined) {
170
- throw new Error("Field is required");
183
+ throw new ValidationError("Field is required", null, value);
171
184
  }
172
185
  if (
173
186
  value !== undefined &&
@@ -175,8 +188,10 @@ class DateTimeField extends BaoBaseField {
175
188
  typeof value !== "number" &&
176
189
  typeof value !== "string"
177
190
  ) {
178
- throw new Error(
191
+ throw new ValidationError(
179
192
  "DateTimeField value must be a Date object, timestamp number, or ISO string",
193
+ null,
194
+ value,
180
195
  );
181
196
  }
182
197
  }
@@ -376,21 +391,25 @@ class UlidField extends BaoBaseField {
376
391
 
377
392
  validate(value) {
378
393
  if (!value && !this.autoAssign) {
379
- throw new Error("ULID is required");
394
+ throw new ValidationError("ULID is required", null, value);
380
395
  }
381
396
 
382
397
  if (value) {
383
398
  // Check if it's a valid ULID format
384
399
  // ULIDs are 26 characters, uppercase alphanumeric
385
400
  if (!/^[0-9A-Z]{26}$/.test(value)) {
386
- throw new Error("Invalid ULID format");
401
+ throw new ValidationError("Invalid ULID format", null, value);
387
402
  }
388
403
 
389
404
  try {
390
405
  // Attempt to decode the timestamp to verify it's valid
391
406
  decodeTime(value);
392
407
  } catch (error) {
393
- throw new Error("Invalid ULID: could not decode timestamp");
408
+ throw new ValidationError(
409
+ "Invalid ULID: could not decode timestamp",
410
+ null,
411
+ value,
412
+ );
394
413
  }
395
414
  }
396
415
  return true;
@@ -421,7 +440,7 @@ class RelatedField extends BaoBaseField {
421
440
 
422
441
  validate(value) {
423
442
  if (this.required && !value) {
424
- throw new Error("Field is required");
443
+ throw new ValidationError("Field is required", null, value);
425
444
  }
426
445
  // Allow both string IDs and model instances
427
446
  if (
@@ -429,8 +448,10 @@ class RelatedField extends BaoBaseField {
429
448
  typeof value !== "string" &&
430
449
  (!value.getPrimaryId || typeof value.getPrimaryId !== "function")
431
450
  ) {
432
- throw new Error(
451
+ throw new ValidationError(
433
452
  "Related field value must be a string ID or model instance",
453
+ null,
454
+ value,
434
455
  );
435
456
  }
436
457
  return true;
@@ -475,7 +496,11 @@ class CounterField extends BaoBaseField {
475
496
  }
476
497
  // Accept regular integer values
477
498
  if (!Number.isInteger(value)) {
478
- throw new Error("CounterField value must be an integer");
499
+ throw new ValidationError(
500
+ "CounterField value must be an integer",
501
+ null,
502
+ value,
503
+ );
479
504
  }
480
505
  }
481
506
  return true;
@@ -576,7 +601,11 @@ class BinaryField extends BaoBaseField {
576
601
  !(value instanceof Buffer) &&
577
602
  !(value instanceof Uint8Array)
578
603
  ) {
579
- throw new Error("BinaryField value must be a Buffer or Uint8Array");
604
+ throw new ValidationError(
605
+ "BinaryField value must be a Buffer or Uint8Array",
606
+ null,
607
+ value,
608
+ );
580
609
  }
581
610
  return true;
582
611
  }
@@ -593,7 +622,11 @@ class BinaryField extends BaoBaseField {
593
622
  }
594
623
 
595
624
  toGsi(value) {
596
- throw new Error("BinaryField does not support GSI conversion");
625
+ throw new ValidationError(
626
+ "BinaryField does not support GSI conversion",
627
+ null,
628
+ value,
629
+ );
597
630
  }
598
631
  }
599
632
 
@@ -619,7 +652,11 @@ class VersionField extends BaoBaseField {
619
652
  if (value !== undefined) {
620
653
  // Verify it's a valid ULID string
621
654
  if (typeof value !== "string" || value.length !== 26) {
622
- throw new Error("VersionField value must be a valid ULID");
655
+ throw new ValidationError(
656
+ "VersionField value must be a valid ULID",
657
+ null,
658
+ value,
659
+ );
623
660
  }
624
661
  }
625
662
  return true;
@@ -654,7 +691,11 @@ class BooleanField extends BaoBaseField {
654
691
  validate(value) {
655
692
  super.validate(value);
656
693
  if (value !== undefined && value !== null && typeof value !== "boolean") {
657
- throw new Error("BooleanField value must be a boolean");
694
+ throw new ValidationError(
695
+ "BooleanField value must be a boolean",
696
+ null,
697
+ value,
698
+ );
658
699
  }
659
700
  return true;
660
701
  }
@@ -699,7 +740,7 @@ class TtlField extends DateTimeField {
699
740
  if (value === null || value === undefined) {
700
741
  return true; // Allow null/undefined for field removal
701
742
  }
702
- return super.validate(value); // Use parent validation for dates
743
+ super.validate(value); // Use parent validation for dates
703
744
  }
704
745
 
705
746
  toDy(value) {
@@ -714,7 +755,11 @@ class TtlField extends DateTimeField {
714
755
  } else {
715
756
  date = new Date(value);
716
757
  if (isNaN(date.getTime())) {
717
- throw new Error("Invalid date value provided for TTL field");
758
+ throw new ValidationError(
759
+ "Invalid date value provided for TTL field",
760
+ null,
761
+ value,
762
+ );
718
763
  }
719
764
  }
720
765
 
@@ -1,3 +1,6 @@
1
+ const { defaultLogger: logger } = require("./utils/logger");
2
+ const { QueryError, ValidationError } = require("./exceptions");
3
+
1
4
  /**
2
5
  * Supporting class for building DynamoDB filter expressions.
3
6
  * @class
@@ -59,20 +62,22 @@ class FilterExpressionBuilder {
59
62
  case "$beginsWith":
60
63
  return `begins_with(${nameKey}, ${this.generateValue(convertedValue)})`;
61
64
  case "$in":
62
- if (!Array.isArray(convertedValue)) {
63
- throw new Error("$in operator requires an array value");
65
+ if (!Array.isArray(value)) {
66
+ throw new ValidationError("$in operator requires an array value");
64
67
  }
65
- const valueKeys = convertedValue.map((v) => this.generateValue(v));
68
+ const valueKeys = value.map((v) => this.generateValue(v));
66
69
  return `${nameKey} IN (${valueKeys.join(", ")})`;
67
70
  case "$exists":
68
71
  if (typeof value !== "boolean") {
69
- throw new Error("$exists operator requires a boolean value");
72
+ throw new ValidationError(
73
+ "$exists operator requires a boolean value",
74
+ );
70
75
  }
71
76
  return value
72
77
  ? `attribute_exists(${nameKey})`
73
78
  : `attribute_not_exists(${nameKey})`;
74
79
  default:
75
- throw new Error(`Unsupported operator: ${operator}`);
80
+ throw new QueryError(`Unsupported operator: ${operator}`);
76
81
  }
77
82
  }
78
83
 
@@ -89,7 +94,7 @@ class FilterExpressionBuilder {
89
94
 
90
95
  const operators = Object.keys(condition);
91
96
  if (operators.length === 0) {
92
- throw new Error(`Empty condition object for field: ${fieldName}`);
97
+ throw new QueryError(`Empty condition object for field: ${fieldName}`);
93
98
  }
94
99
 
95
100
  const expressions = operators.map((operator) => {
@@ -107,7 +112,7 @@ class FilterExpressionBuilder {
107
112
  // Build expression for logical operators
108
113
  buildLogicalExpression(operator, conditions, model) {
109
114
  if (!Array.isArray(conditions)) {
110
- throw new Error(`${operator} requires an array of conditions`);
115
+ throw new QueryError(`${operator} requires an array of conditions`);
111
116
  }
112
117
 
113
118
  const expressions = conditions.map((condition) => {
@@ -208,8 +213,9 @@ class FilterExpressionBuilder {
208
213
  }
209
214
 
210
215
  // Validate field exists in model
211
- if (!model.fields[key]) {
212
- throw new Error(`Unknown field in filter: ${key}`);
216
+ const field = model.fields[key];
217
+ if (!field) {
218
+ throw new QueryError(`Unknown field in filter: ${key}`);
213
219
  }
214
220
 
215
221
  // Recursively validate nested conditions
@@ -221,21 +227,20 @@ class FilterExpressionBuilder {
221
227
  ) {
222
228
  const operators = Object.keys(value);
223
229
  operators.forEach((op) => {
224
- if (
225
- ![
226
- "$eq",
227
- "$ne",
228
- "$gt",
229
- "$gte",
230
- "$lt",
231
- "$lte",
232
- "$in",
233
- "$contains",
234
- "$beginsWith",
235
- "$exists",
236
- ].includes(op)
237
- ) {
238
- throw new Error(`Invalid operator ${op} for field ${key}`);
230
+ const validOperators = [
231
+ "$eq",
232
+ "$ne",
233
+ "$gt",
234
+ "$gte",
235
+ "$lt",
236
+ "$lte",
237
+ "$in",
238
+ "$contains",
239
+ "$beginsWith",
240
+ "$exists",
241
+ ];
242
+ if (!validOperators.includes(op)) {
243
+ throw new QueryError(`Invalid operator ${op} for field ${key}`);
239
244
  }
240
245
  });
241
246
  }
package/src/index.js CHANGED
@@ -6,6 +6,8 @@ const { ModelManager } = require("./model-manager");
6
6
  const { defaultLogger: logger } = require("./utils/logger");
7
7
  const fields = require("./fields");
8
8
  const constants = require("./constants");
9
+ const exceptions = require("./exceptions");
10
+ const { ConfigurationError } = require("./exceptions");
9
11
 
10
12
  const {
11
13
  BaoModel,
@@ -35,8 +37,7 @@ function findModelFiles(dir) {
35
37
 
36
38
  function _registerModels(manager = null, modelsDir = null) {
37
39
  if (!modelsDir) {
38
- throw new Error("modelsDir is required");
39
- return;
40
+ throw new ConfigurationError("modelsDir is required");
40
41
  }
41
42
 
42
43
  const modelFiles = findModelFiles(modelsDir);
@@ -116,6 +117,9 @@ const firstExport = {
116
117
  // Export the constants module directly
117
118
  constants,
118
119
 
120
+ // Export the exceptions module
121
+ exceptions,
122
+
119
123
  models: {},
120
124
  };
121
125
 
@@ -1,3 +1,6 @@
1
+ const { defaultLogger: logger } = require("./utils/logger");
2
+ const { QueryError } = require("./exceptions");
3
+
1
4
  class KeyConditionBuilder {
2
5
  constructor() {
3
6
  this.names = {};
@@ -29,20 +32,27 @@ class KeyConditionBuilder {
29
32
  validateSortKeyField(model, indexName, fieldName) {
30
33
  const index = model.indexes[indexName];
31
34
  if (!index) {
32
- throw new Error(`Index "${indexName}" not found in ${model.name}`);
35
+ throw new QueryError(
36
+ `Index "${indexName}" not found in ${model.name}`,
37
+ indexName,
38
+ );
33
39
  }
34
40
 
35
41
  if (index.sk === "modelPrefix") {
36
- throw new Error(
42
+ throw new QueryError(
37
43
  `Cannot query by sort key on index "${indexName}" as it uses modelPrefix`,
44
+ indexName,
45
+ fieldName,
38
46
  );
39
47
  }
40
48
 
41
49
  const skField = index.sk;
42
50
  if (skField !== fieldName) {
43
- throw new Error(
51
+ throw new QueryError(
44
52
  `Field "${fieldName}" is not the sort key for index "${indexName}". ` +
45
53
  `Expected "${skField}"`,
54
+ indexName,
55
+ fieldName,
46
56
  );
47
57
  }
48
58
  }
@@ -86,7 +96,9 @@ class KeyConditionBuilder {
86
96
 
87
97
  case "$between":
88
98
  if (!Array.isArray(value) || value.length !== 2) {
89
- throw new Error("$between requires an array with exactly 2 elements");
99
+ throw new QueryError(
100
+ "$between requires an array with exactly 2 elements",
101
+ );
90
102
  }
91
103
  return {
92
104
  condition: `${nameKey} BETWEEN ${this.generateValue(value[0])} AND ${this.generateValue(value[1])}`,
@@ -111,7 +123,7 @@ class KeyConditionBuilder {
111
123
  };
112
124
 
113
125
  default:
114
- throw new Error(`Unsupported sort key operator: ${operator}`);
126
+ throw new QueryError(`Unsupported sort key operator: ${operator}`);
115
127
  }
116
128
  }
117
129
 
@@ -167,7 +179,7 @@ class KeyConditionBuilder {
167
179
  buildKeyCondition(model, indexName, condition, gsiSortKeyName) {
168
180
  // Validate the condition format
169
181
  if (!condition || typeof condition !== "object") {
170
- throw new Error("Invalid condition format");
182
+ throw new QueryError("Invalid condition format");
171
183
  }
172
184
 
173
185
  const [[fieldName, fieldCondition]] = Object.entries(condition);
@@ -175,8 +187,10 @@ class KeyConditionBuilder {
175
187
  // Validate that this field is the sort key for the index
176
188
  const index = model.indexes[indexName];
177
189
  if (!index || index.sk !== fieldName) {
178
- throw new Error(
190
+ throw new QueryError(
179
191
  `Field "${fieldName}" is not the sort key for index "${indexName}"`,
192
+ indexName,
193
+ fieldName,
180
194
  );
181
195
  }
182
196
 
@@ -201,13 +215,13 @@ class KeyConditionBuilder {
201
215
  "$lte",
202
216
  ];
203
217
  if (!validOperators.includes(operator)) {
204
- throw new Error(`Unsupported sort key operator: ${operator}`);
218
+ throw new QueryError(`Unsupported sort key operator: ${operator}`);
205
219
  }
206
220
 
207
221
  switch (operator) {
208
222
  case "$between":
209
223
  if (!Array.isArray(value) || value.length !== 2) {
210
- throw new Error(
224
+ throw new QueryError(
211
225
  "$between requires an array with exactly 2 elements",
212
226
  );
213
227
  }
@@ -238,20 +252,20 @@ class KeyConditionBuilder {
238
252
  };
239
253
 
240
254
  default:
241
- throw new Error(`Unsupported sort key operator: ${operator}`);
255
+ throw new QueryError(`Unsupported sort key operator: ${operator}`);
256
+ }
257
+ } else {
258
+ // Handle direct value (treat as equality)
259
+ if (fieldCondition === undefined) {
260
+ throw new QueryError("Sort key condition value cannot be undefined");
242
261
  }
243
- }
244
262
 
245
- // Handle simple value case (treated as equality)
246
- if (fieldCondition === undefined) {
247
- throw new Error("Sort key condition value cannot be undefined");
263
+ return {
264
+ condition: `${nameKey} = :sortKeyValue`,
265
+ names,
266
+ values: { ":sortKeyValue": field.toGsi(fieldCondition) },
267
+ };
248
268
  }
249
-
250
- return {
251
- condition: `${nameKey} = :sortKeyValue`,
252
- names,
253
- values: { ":sortKeyValue": field.toGsi(fieldCondition) },
254
- };
255
269
  }
256
270
  }
257
271
 
@@ -8,6 +8,11 @@ const { pluginManager } = require("../plugin-manager");
8
8
  const { retryOperation } = require("../utils/retry-helper");
9
9
  const assert = require("assert");
10
10
  const { FilterExpressionBuilder } = require("../filter-expression");
11
+ const {
12
+ ItemNotFoundError,
13
+ ConditionalError,
14
+ ValidationError,
15
+ } = require("../exceptions");
11
16
 
12
17
  const MutationMethods = {
13
18
  /**
@@ -117,7 +122,7 @@ const MutationMethods = {
117
122
 
118
123
  const item = await this.find(primaryId, { batchDelay: 0 });
119
124
  if (!item) {
120
- throw new Error("Item not found");
125
+ throw new ItemNotFoundError("Item not found", primaryId);
121
126
  }
122
127
 
123
128
  // Check if we need to clean up any unique constraints
@@ -232,6 +237,7 @@ const MutationMethods = {
232
237
  "write",
233
238
  false,
234
239
  );
240
+
235
241
  return deletedItem;
236
242
  } catch (error) {
237
243
  if (
@@ -239,7 +245,11 @@ const MutationMethods = {
239
245
  (error.name === "TransactionCanceledException" &&
240
246
  error.CancellationReasons?.[0]?.Code === "ConditionalCheckFailed")
241
247
  ) {
242
- throw new Error("Delete condition not met");
248
+ throw new ConditionalError(
249
+ "Delete condition not met",
250
+ "delete",
251
+ options.condition,
252
+ );
243
253
  }
244
254
  throw error;
245
255
  }
@@ -291,12 +301,12 @@ const MutationMethods = {
291
301
  ...currentItem.getConsumedCapacity(),
292
302
  ];
293
303
  } else {
294
- throw new Error("Item not found");
304
+ throw new ItemNotFoundError("Item not found", primaryId);
295
305
  }
296
306
  }
297
307
 
298
308
  if (!isNew && !currentItem) {
299
- throw new Error("Item not found");
309
+ throw new ItemNotFoundError("Item not found", primaryId);
300
310
  }
301
311
 
302
312
  const transactItems = [];
@@ -338,7 +348,11 @@ const MutationMethods = {
338
348
  (jsUpdates[fieldName] === undefined ||
339
349
  jsUpdates[fieldName] === null)
340
350
  ) {
341
- throw new Error(`Field is required: ${fieldName} `);
351
+ throw new ValidationError(
352
+ `Field is required: ${fieldName}`,
353
+ fieldName,
354
+ jsUpdates[fieldName],
355
+ );
342
356
  }
343
357
  }
344
358
  }
@@ -489,7 +503,7 @@ const MutationMethods = {
489
503
  logger.debug("savedItem.getPrimaryId()", savedItem.getPrimaryId());
490
504
 
491
505
  if (!savedItem.exists()) {
492
- throw new Error("Failed to fetch saved item");
506
+ throw new ConditionalError("Failed to fetch saved item", "update");
493
507
  }
494
508
 
495
509
  // Set the consumed capacity from the transaction
@@ -528,15 +542,34 @@ const MutationMethods = {
528
542
  false,
529
543
  );
530
544
  savedItem._addConsumedCapacity(consumedCapacity, "read", false);
545
+
546
+ if (!savedItem.exists()) {
547
+ throw new ConditionalError("Failed to fetch saved item", "update");
548
+ }
549
+
531
550
  return savedItem;
532
551
  }
533
552
  } catch (error) {
534
553
  logger.error("Error in _saveItem", error);
535
554
  if (error.name === "ConditionalCheckFailedException") {
536
- throw new Error("Condition check failed", error);
555
+ throw new ConditionalError("Condition check failed", "update", error);
537
556
  }
538
557
 
539
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
540
573
  await this._validateUniqueConstraints(
541
574
  jsUpdates,
542
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
package/src/model.js CHANGED
@@ -25,6 +25,12 @@ const {
25
25
 
26
26
  const GID_SEPARATOR = "##__SK__##";
27
27
  const { UNIQUE_CONSTRAINT_KEY, SYSTEM_FIELDS } = require("./constants");
28
+ const {
29
+ ConfigurationError,
30
+ ValidationError,
31
+ QueryError,
32
+ DataFormatError,
33
+ } = require("./exceptions");
28
34
 
29
35
  /**
30
36
  * @description
@@ -83,7 +89,10 @@ class BaoModel {
83
89
  }
84
90
 
85
91
  if (!fieldDef) {
86
- throw new Error(`Field ${fieldName} not found in ${this.name} fields`);
92
+ throw new ConfigurationError(
93
+ `Field ${fieldName} not found in ${this.name} fields`,
94
+ this.name,
95
+ );
87
96
  }
88
97
 
89
98
  return fieldDef;
@@ -91,7 +100,9 @@ class BaoModel {
91
100
 
92
101
  static _getPkValue(data) {
93
102
  if (!data) {
94
- throw new Error("Data object is required for static _getPkValue call");
103
+ throw new ValidationError(
104
+ "Data object is required for static _getPkValue call",
105
+ );
95
106
  }
96
107
 
97
108
  const pkValue =
@@ -106,7 +117,9 @@ class BaoModel {
106
117
 
107
118
  static _getSkValue(data) {
108
119
  if (!data) {
109
- throw new Error("Data object is required for static _getSkValue call");
120
+ throw new ValidationError(
121
+ "Data object is required for static _getSkValue call",
122
+ );
110
123
  }
111
124
 
112
125
  if (this.primaryKey.sk === "modelPrefix") {
@@ -228,18 +241,26 @@ class BaoModel {
228
241
  // dynamo string keys. No test prefix or model prefix is applied.
229
242
  static _getPrimaryKeyValues(data) {
230
243
  if (!data) {
231
- throw new Error("Data object is required for _getPrimaryKeyValues call");
244
+ throw new ValidationError(
245
+ "Data object is required for _getPrimaryKeyValues call",
246
+ );
232
247
  }
233
248
 
234
249
  const pkField = this._getField(this.primaryKey.pk);
235
250
  const skField = this._getField(this.primaryKey.sk);
236
251
 
237
252
  if (skField === undefined && this.primaryKey.sk !== "modelPrefix") {
238
- throw new Error(`SK field is required for getPkSk call`);
253
+ throw new ConfigurationError(
254
+ `SK field is required for getPkSk call`,
255
+ this.name,
256
+ );
239
257
  }
240
258
 
241
259
  if (pkField === undefined && this.primaryKey.pk !== "modelPrefix") {
242
- throw new Error(`PK field is required for getPkSk call`);
260
+ throw new ConfigurationError(
261
+ `PK field is required for getPkSk call`,
262
+ this.name,
263
+ );
243
264
  }
244
265
 
245
266
  // If the field is set, use the GSI value, otherwise use the raw value
@@ -256,7 +277,7 @@ class BaoModel {
256
277
  pkValue === null ||
257
278
  skValue === null
258
279
  ) {
259
- throw new Error(`PK and SK must be defined to get a PkSk`);
280
+ throw new ValidationError(`PK and SK must be defined to get a PkSk`);
260
281
  }
261
282
 
262
283
  let key = {
@@ -269,6 +290,23 @@ class BaoModel {
269
290
  return key;
270
291
  }
271
292
 
293
+ /**
294
+ * @description
295
+ * Make a primary ID from a pk and sk.
296
+ * @param {string} pk - The partition key.
297
+ * @param {string} sk - The sort key.
298
+ * @returns {string} The primary ID.
299
+ */
300
+ static makePrimaryId(pk, sk) {
301
+ if (this.primaryKey.pk === "modelPrefix") {
302
+ return sk;
303
+ } else if (this.primaryKey.sk === "modelPrefix") {
304
+ return pk;
305
+ } else {
306
+ return pk + GID_SEPARATOR + sk;
307
+ }
308
+ }
309
+
272
310
  /**
273
311
  * @description
274
312
  * Static version of {@link BaoModel#getPrimaryId}.
@@ -280,15 +318,7 @@ class BaoModel {
280
318
  const pkSk = this._getPrimaryKeyValues(data);
281
319
  logger.debug("getPrimaryId", pkSk);
282
320
 
283
- let primaryId;
284
- if (this.primaryKey.pk === "modelPrefix") {
285
- primaryId = pkSk.sk;
286
- } else if (this.primaryKey.sk === "modelPrefix") {
287
- primaryId = pkSk.pk;
288
- } else {
289
- primaryId = pkSk.pk + GID_SEPARATOR + pkSk.sk;
290
- }
291
-
321
+ let primaryId = this.makePrimaryId(pkSk.pk, pkSk.sk);
292
322
  return primaryId;
293
323
  }
294
324
 
@@ -306,7 +336,7 @@ class BaoModel {
306
336
 
307
337
  static _parsePrimaryId(primaryId) {
308
338
  if (!primaryId) {
309
- throw new Error("Primary ID is required to parse");
339
+ throw new DataFormatError("Primary ID is required to parse");
310
340
  }
311
341
 
312
342
  if (primaryId.indexOf(GID_SEPARATOR) !== -1) {
@@ -318,7 +348,7 @@ class BaoModel {
318
348
  } else if (this.primaryKey.sk === "modelPrefix") {
319
349
  return { pk: primaryId, sk: this.modelPrefix };
320
350
  } else {
321
- throw new Error(`Invalid primary ID: ${primaryId}`);
351
+ throw new DataFormatError(`Invalid primary ID: ${primaryId}`);
322
352
  }
323
353
  }
324
354
  }
@@ -440,7 +470,10 @@ class BaoModel {
440
470
 
441
471
  const field = this.constructor.fields[fieldName];
442
472
  if (!field || !field.modelName) {
443
- throw new Error(`Field ${fieldName} is not a valid relation field`);
473
+ throw new ConfigurationError(
474
+ `Field ${fieldName} is not a valid relation field`,
475
+ this.constructor.name,
476
+ );
444
477
  }
445
478
 
446
479
  const value = this[fieldName];
@@ -508,7 +541,10 @@ class BaoModel {
508
541
  getRelated(fieldName) {
509
542
  const field = this.constructor.fields[fieldName];
510
543
  if (!(field instanceof RelatedFieldClass)) {
511
- throw new Error(`Field ${fieldName} is not a RelatedField`);
544
+ throw new ConfigurationError(
545
+ `Field ${fieldName} is not a RelatedField`,
546
+ this.constructor.name,
547
+ );
512
548
  }
513
549
  return this._relatedObjects[fieldName];
514
550
  }
@@ -529,13 +565,17 @@ class BaoModel {
529
565
  ) {
530
566
  const constraint = this.uniqueConstraints[constraintName];
531
567
  if (!constraint) {
532
- throw new Error(
568
+ throw new ConfigurationError(
533
569
  `Unknown unique constraint '${constraintName}' in ${this.name}`,
570
+ this.name,
534
571
  );
535
572
  }
536
573
 
537
574
  if (!value) {
538
- throw new Error(`${constraint.field} value is required`);
575
+ throw new ValidationError(
576
+ `${constraint.field} value is required`,
577
+ constraint.field,
578
+ );
539
579
  }
540
580
 
541
581
  const key = this._formatUniqueConstraintKey(
@@ -561,7 +601,7 @@ class BaoModel {
561
601
  const item = await this.find(result.Item.relatedId, { loaderContext });
562
602
 
563
603
  if (item) {
564
- item._addConsumedCapacity(result.ConsumedCapacity);
604
+ item._addConsumedCapacity(result.ConsumedCapacity, "read");
565
605
  }
566
606
 
567
607
  return item;
@@ -584,30 +624,30 @@ class BaoModel {
584
624
  this._addConsumedCapacity(capacity, type, fromContext);
585
625
  }
586
626
 
587
- _addConsumedCapacity(capacity, type = "read", fromContext = false) {
588
- if (type !== "read" && type !== "write" && type !== "total") {
589
- throw new Error(`Invalid consumed capacity type: ${type}`);
627
+ _addConsumedCapacity(consumedCapacity, type, isRelated = false) {
628
+ if (!["read", "write"].includes(type)) {
629
+ throw new ValidationError(`Invalid consumed capacity type: ${type}`);
590
630
  }
591
631
 
592
- if (!capacity) {
632
+ if (!consumedCapacity) {
593
633
  return;
594
634
  }
595
635
 
596
- if (Array.isArray(capacity)) {
597
- capacity.forEach((item) =>
598
- this._addConsumedCapacity(item, type, fromContext),
636
+ if (Array.isArray(consumedCapacity)) {
637
+ consumedCapacity.forEach((item) =>
638
+ this._addConsumedCapacity(item, type, isRelated),
599
639
  );
600
640
  } else {
601
- if (capacity.consumedCapacity) {
641
+ if (consumedCapacity.consumedCapacity) {
602
642
  this._consumedCapacity.push({
603
- consumedCapacity: capacity.consumedCapacity,
604
- fromContext: capacity.fromContext || fromContext,
605
- type: capacity.type || type,
643
+ consumedCapacity: consumedCapacity.consumedCapacity,
644
+ fromContext: consumedCapacity.fromContext || isRelated,
645
+ type: consumedCapacity.type || type,
606
646
  });
607
647
  } else {
608
648
  this._consumedCapacity.push({
609
- consumedCapacity: capacity,
610
- fromContext: fromContext,
649
+ consumedCapacity: consumedCapacity,
650
+ fromContext: isRelated,
611
651
  type: type,
612
652
  });
613
653
  }
@@ -624,8 +664,8 @@ class BaoModel {
624
664
  * @returns {number} The numeric consumed capacity.
625
665
  */
626
666
  getNumericConsumedCapacity(type, includeRelated = false) {
627
- if (type !== "read" && type !== "write" && type !== "total") {
628
- throw new Error(`Invalid consumed capacitytype: ${type}`);
667
+ if (!["read", "write", "total"].includes(type)) {
668
+ throw new ValidationError(`Invalid consumed capacity type: ${type}`);
629
669
  }
630
670
 
631
671
  let consumedCapacity = this._consumedCapacity;