dyno-table 0.2.0-0 → 1.0.0-alpha.1

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.
Files changed (96) hide show
  1. package/README.md +182 -577
  2. package/dist/{table.cjs → index.cjs} +175 -87
  3. package/dist/index.d.cts +2971 -0
  4. package/dist/index.d.ts +2971 -0
  5. package/dist/{table.js → index.js} +127 -86
  6. package/package.json +10 -77
  7. package/dist/builder-types-C_PDZhnP.d.ts +0 -118
  8. package/dist/builder-types-DtwbqMeF.d.cts +0 -118
  9. package/dist/builders/condition-check-builder.cjs +0 -394
  10. package/dist/builders/condition-check-builder.cjs.map +0 -1
  11. package/dist/builders/condition-check-builder.d.cts +0 -157
  12. package/dist/builders/condition-check-builder.d.ts +0 -157
  13. package/dist/builders/condition-check-builder.js +0 -392
  14. package/dist/builders/condition-check-builder.js.map +0 -1
  15. package/dist/builders/delete-builder.cjs +0 -405
  16. package/dist/builders/delete-builder.cjs.map +0 -1
  17. package/dist/builders/delete-builder.d.cts +0 -166
  18. package/dist/builders/delete-builder.d.ts +0 -166
  19. package/dist/builders/delete-builder.js +0 -403
  20. package/dist/builders/delete-builder.js.map +0 -1
  21. package/dist/builders/paginator.cjs +0 -199
  22. package/dist/builders/paginator.cjs.map +0 -1
  23. package/dist/builders/paginator.d.cts +0 -179
  24. package/dist/builders/paginator.d.ts +0 -179
  25. package/dist/builders/paginator.js +0 -197
  26. package/dist/builders/paginator.js.map +0 -1
  27. package/dist/builders/put-builder.cjs +0 -476
  28. package/dist/builders/put-builder.cjs.map +0 -1
  29. package/dist/builders/put-builder.d.cts +0 -274
  30. package/dist/builders/put-builder.d.ts +0 -274
  31. package/dist/builders/put-builder.js +0 -474
  32. package/dist/builders/put-builder.js.map +0 -1
  33. package/dist/builders/query-builder.cjs +0 -674
  34. package/dist/builders/query-builder.cjs.map +0 -1
  35. package/dist/builders/query-builder.d.cts +0 -6
  36. package/dist/builders/query-builder.d.ts +0 -6
  37. package/dist/builders/query-builder.js +0 -672
  38. package/dist/builders/query-builder.js.map +0 -1
  39. package/dist/builders/transaction-builder.cjs +0 -894
  40. package/dist/builders/transaction-builder.cjs.map +0 -1
  41. package/dist/builders/transaction-builder.d.cts +0 -511
  42. package/dist/builders/transaction-builder.d.ts +0 -511
  43. package/dist/builders/transaction-builder.js +0 -892
  44. package/dist/builders/transaction-builder.js.map +0 -1
  45. package/dist/builders/update-builder.cjs +0 -627
  46. package/dist/builders/update-builder.cjs.map +0 -1
  47. package/dist/builders/update-builder.d.cts +0 -365
  48. package/dist/builders/update-builder.d.ts +0 -365
  49. package/dist/builders/update-builder.js +0 -625
  50. package/dist/builders/update-builder.js.map +0 -1
  51. package/dist/conditions--ld9a78i.d.ts +0 -331
  52. package/dist/conditions-ChhQWd6z.d.cts +0 -331
  53. package/dist/conditions.cjs +0 -59
  54. package/dist/conditions.cjs.map +0 -1
  55. package/dist/conditions.d.cts +0 -3
  56. package/dist/conditions.d.ts +0 -3
  57. package/dist/conditions.js +0 -43
  58. package/dist/conditions.js.map +0 -1
  59. package/dist/entity.cjs +0 -228
  60. package/dist/entity.cjs.map +0 -1
  61. package/dist/entity.d.cts +0 -149
  62. package/dist/entity.d.ts +0 -149
  63. package/dist/entity.js +0 -224
  64. package/dist/entity.js.map +0 -1
  65. package/dist/query-builder-Csror9Iu.d.ts +0 -507
  66. package/dist/query-builder-D2FM9rsu.d.cts +0 -507
  67. package/dist/standard-schema.cjs +0 -4
  68. package/dist/standard-schema.cjs.map +0 -1
  69. package/dist/standard-schema.d.cts +0 -57
  70. package/dist/standard-schema.d.ts +0 -57
  71. package/dist/standard-schema.js +0 -3
  72. package/dist/standard-schema.js.map +0 -1
  73. package/dist/table-BEhBPy2G.d.cts +0 -364
  74. package/dist/table-BW3cmUqr.d.ts +0 -364
  75. package/dist/table.cjs.map +0 -1
  76. package/dist/table.d.cts +0 -12
  77. package/dist/table.d.ts +0 -12
  78. package/dist/table.js.map +0 -1
  79. package/dist/types.cjs +0 -4
  80. package/dist/types.cjs.map +0 -1
  81. package/dist/types.d.cts +0 -22
  82. package/dist/types.d.ts +0 -22
  83. package/dist/types.js +0 -3
  84. package/dist/types.js.map +0 -1
  85. package/dist/utils/partition-key-template.cjs +0 -19
  86. package/dist/utils/partition-key-template.cjs.map +0 -1
  87. package/dist/utils/partition-key-template.d.cts +0 -32
  88. package/dist/utils/partition-key-template.d.ts +0 -32
  89. package/dist/utils/partition-key-template.js +0 -17
  90. package/dist/utils/partition-key-template.js.map +0 -1
  91. package/dist/utils/sort-key-template.cjs +0 -19
  92. package/dist/utils/sort-key-template.cjs.map +0 -1
  93. package/dist/utils/sort-key-template.d.cts +0 -35
  94. package/dist/utils/sort-key-template.d.ts +0 -35
  95. package/dist/utils/sort-key-template.js +0 -17
  96. package/dist/utils/sort-key-template.js.map +0 -1
@@ -1,894 +0,0 @@
1
- 'use strict';
2
-
3
- // src/expression.ts
4
- var generateAttributeName = (params, attr) => {
5
- for (const [existingName, existingAttr] of Object.entries(params.expressionAttributeNames)) {
6
- if (existingAttr === attr) {
7
- return existingName;
8
- }
9
- }
10
- const attrName = `#${Object.keys(params.expressionAttributeNames).length}`;
11
- params.expressionAttributeNames[attrName] = attr;
12
- return attrName;
13
- };
14
- var generateValueName = (params, value) => {
15
- const valueName = `:${params.valueCounter.count++}`;
16
- params.expressionAttributeValues[valueName] = value;
17
- return valueName;
18
- };
19
- var validateCondition = (condition, requiresAttr = true, requiresValue = true) => {
20
- if (requiresAttr && !condition.attr) {
21
- throw new Error(`Attribute is required for ${condition.type} condition`);
22
- }
23
- if (requiresValue && condition.value === void 0) {
24
- throw new Error(`Value is required for ${condition.type} condition`);
25
- }
26
- };
27
- var buildComparisonExpression = (condition, operator, params) => {
28
- validateCondition(condition);
29
- if (!condition.attr) {
30
- throw new Error(`Attribute is required for ${condition.type} condition`);
31
- }
32
- const attrName = generateAttributeName(params, condition.attr);
33
- const valueName = generateValueName(params, condition.value);
34
- return `${attrName} ${operator} ${valueName}`;
35
- };
36
- var buildBetweenExpression = (condition, params) => {
37
- validateCondition(condition);
38
- if (!condition.attr) {
39
- throw new Error(`Attribute is required for ${condition.type} condition`);
40
- }
41
- if (!Array.isArray(condition.value) || condition.value.length !== 2) {
42
- throw new Error("Between condition requires an array of two values");
43
- }
44
- const attrName = generateAttributeName(params, condition.attr);
45
- const lowerName = generateValueName(params, condition.value[0]);
46
- const upperName = generateValueName(params, condition.value[1]);
47
- return `${attrName} BETWEEN ${lowerName} AND ${upperName}`;
48
- };
49
- var buildFunctionExpression = (functionName, condition, params) => {
50
- validateCondition(condition);
51
- if (!condition.attr) {
52
- throw new Error(`Attribute is required for ${condition.type} condition`);
53
- }
54
- const attrName = generateAttributeName(params, condition.attr);
55
- const valueName = generateValueName(params, condition.value);
56
- return `${functionName}(${attrName}, ${valueName})`;
57
- };
58
- var buildAttributeFunction = (functionName, condition, params) => {
59
- validateCondition(condition, true, false);
60
- if (!condition.attr) {
61
- throw new Error(`Attribute is required for ${condition.type} condition`);
62
- }
63
- const attrName = generateAttributeName(params, condition.attr);
64
- return `${functionName}(${attrName})`;
65
- };
66
- var buildLogicalExpression = (operator, conditions, params) => {
67
- if (!conditions || conditions.length === 0) {
68
- throw new Error(`At least one condition is required for ${operator} expression`);
69
- }
70
- const expressions = conditions.map((c) => buildExpression(c, params));
71
- return `(${expressions.join(` ${operator} `)})`;
72
- };
73
- var buildExpression = (condition, params) => {
74
- if (!condition) return "";
75
- try {
76
- const expressionBuilders = {
77
- eq: () => buildComparisonExpression(condition, "=", params),
78
- ne: () => buildComparisonExpression(condition, "<>", params),
79
- lt: () => buildComparisonExpression(condition, "<", params),
80
- lte: () => buildComparisonExpression(condition, "<=", params),
81
- gt: () => buildComparisonExpression(condition, ">", params),
82
- gte: () => buildComparisonExpression(condition, ">=", params),
83
- between: () => buildBetweenExpression(condition, params),
84
- beginsWith: () => buildFunctionExpression("begins_with", condition, params),
85
- contains: () => buildFunctionExpression("contains", condition, params),
86
- attributeExists: () => buildAttributeFunction("attribute_exists", condition, params),
87
- attributeNotExists: () => buildAttributeFunction("attribute_not_exists", condition, params),
88
- and: () => {
89
- if (!condition.conditions) {
90
- throw new Error("Conditions array is required for AND operator");
91
- }
92
- return buildLogicalExpression("AND", condition.conditions, params);
93
- },
94
- or: () => {
95
- if (!condition.conditions) {
96
- throw new Error("Conditions array is required for OR operator");
97
- }
98
- return buildLogicalExpression("OR", condition.conditions, params);
99
- },
100
- not: () => {
101
- if (!condition.condition) {
102
- throw new Error("Condition is required for NOT operator");
103
- }
104
- return `NOT (${buildExpression(condition.condition, params)})`;
105
- }
106
- };
107
- const builder = expressionBuilders[condition.type];
108
- if (!builder) {
109
- throw new Error(`Unknown condition type: ${condition.type}`);
110
- }
111
- return builder();
112
- } catch (error) {
113
- if (error instanceof Error) {
114
- console.error(`Error building expression for condition type ${condition.type}:`, error.message);
115
- } else {
116
- console.error(`Error building expression for condition type ${condition.type}:`, error);
117
- }
118
- throw error;
119
- }
120
- };
121
- var prepareExpressionParams = (condition) => {
122
- if (!condition) return {};
123
- const params = {
124
- expressionAttributeNames: {},
125
- expressionAttributeValues: {},
126
- valueCounter: { count: 0 }
127
- };
128
- const expression = buildExpression(condition, params);
129
- return {
130
- expression,
131
- names: Object.keys(params.expressionAttributeNames).length > 0 ? params.expressionAttributeNames : void 0,
132
- values: Object.keys(params.expressionAttributeValues).length > 0 ? params.expressionAttributeValues : void 0
133
- };
134
- };
135
-
136
- // src/utils/debug-expression.ts
137
- function debugCommand(command) {
138
- const result = {};
139
- function replaceAliases(expressionString) {
140
- if (!expressionString) {
141
- return expressionString;
142
- }
143
- let replacedString = expressionString;
144
- for (const alias in command.expressionAttributeNames) {
145
- const attributeName = command.expressionAttributeNames[alias];
146
- const regex = new RegExp(alias, "g");
147
- replacedString = replacedString.replace(regex, attributeName);
148
- }
149
- for (const alias in command.expressionAttributeValues) {
150
- let attributeValue = command.expressionAttributeValues[alias];
151
- if (attributeValue instanceof Set) {
152
- const array = Array.from(attributeValue);
153
- attributeValue = `Set(${array.length}){${array.map((v) => JSON.stringify(v)).join(", ")}}`;
154
- } else {
155
- attributeValue = JSON.stringify(attributeValue);
156
- }
157
- const regex = new RegExp(alias, "g");
158
- replacedString = replacedString.replace(regex, attributeValue);
159
- }
160
- return replacedString;
161
- }
162
- if (command.updateExpression) {
163
- result.updateExpression = replaceAliases(command.updateExpression);
164
- }
165
- if (command.conditionExpression) {
166
- result.conditionExpression = replaceAliases(command.conditionExpression);
167
- }
168
- if (command.filterExpression) {
169
- result.filterExpression = replaceAliases(command.filterExpression);
170
- }
171
- if (command.keyConditionExpression) {
172
- result.keyConditionExpression = replaceAliases(command.keyConditionExpression);
173
- }
174
- if (command.projectionExpression) {
175
- result.projectionExpression = replaceAliases(command.projectionExpression);
176
- }
177
- return {
178
- raw: command,
179
- readable: result
180
- };
181
- }
182
-
183
- // src/utils/debug-transaction.ts
184
- function debugTransactionItem(item) {
185
- const result = {
186
- type: item.type,
187
- tableName: item.params.tableName
188
- };
189
- if ("key" in item.params) {
190
- result.key = item.params.key;
191
- }
192
- if (item.type === "Put") {
193
- result.item = item.params.item;
194
- }
195
- switch (item.type) {
196
- case "Put":
197
- case "Delete":
198
- case "ConditionCheck":
199
- result.readable = debugCommand(item.params).readable;
200
- break;
201
- case "Update":
202
- result.readable = debugCommand(item.params).readable;
203
- break;
204
- }
205
- return result;
206
- }
207
- function debugTransaction(items) {
208
- return items.map((item) => debugTransactionItem(item));
209
- }
210
-
211
- // src/builders/transaction-builder.ts
212
- var TransactionBuilder = class {
213
- items = [];
214
- options = {};
215
- indexConfig;
216
- executor;
217
- constructor(executor, indexConfig) {
218
- this.executor = executor;
219
- this.indexConfig = indexConfig;
220
- }
221
- /**
222
- * Checks if an item with the same primary key already exists in the transaction
223
- * @private
224
- */
225
- checkForDuplicateItem(tableName, newItem) {
226
- const pkName = this.indexConfig.partitionKey;
227
- const skName = this.indexConfig.sortKey ?? "";
228
- const pkValue = newItem[pkName];
229
- const skValue = skName ? newItem[skName] : void 0;
230
- if (!pkValue) {
231
- throw new Error(`Primary key value for '${pkName}' is missing`);
232
- }
233
- const duplicateItem = this.items.find((item) => {
234
- let itemKey;
235
- let itemTableName;
236
- switch (item.type) {
237
- case "Put":
238
- itemTableName = item.params.tableName;
239
- itemKey = item.params.item;
240
- break;
241
- case "Update":
242
- case "Delete":
243
- case "ConditionCheck":
244
- itemTableName = item.params.tableName;
245
- itemKey = item.params.key;
246
- break;
247
- }
248
- if (itemTableName === tableName && itemKey) {
249
- const itemPkValue = itemKey[pkName];
250
- const itemSkValue = skName ? itemKey[skName] : void 0;
251
- if (itemPkValue === pkValue) {
252
- if (skValue === void 0 && itemSkValue === void 0) {
253
- return true;
254
- }
255
- if (skValue !== void 0 && itemSkValue !== void 0 && skValue === itemSkValue) {
256
- return true;
257
- }
258
- }
259
- }
260
- return false;
261
- });
262
- if (duplicateItem) {
263
- throw new Error(
264
- `Duplicate item detected in transaction: Table=${tableName}, ${pkName}=${String(pkValue)}, ${skName}=${skValue !== void 0 ? String(skValue) : "undefined"}. DynamoDB transactions do not allow multiple operations on the same item.`
265
- );
266
- }
267
- }
268
- createKeyForPrimaryIndex(key) {
269
- const keyCondition = {
270
- [this.indexConfig.partitionKey]: key.pk
271
- };
272
- if (this.indexConfig.sortKey) {
273
- if (key.sk === void 0) {
274
- throw new Error("Sort key is required for delete operation");
275
- }
276
- keyCondition[this.indexConfig.sortKey] = key.sk;
277
- }
278
- return keyCondition;
279
- }
280
- /**
281
- * Adds a put operation to the transaction.
282
- * Use this method when you need to:
283
- * - Insert new items as part of a transaction
284
- * - Replace existing items atomically
285
- * - Ensure items meet certain conditions before insertion
286
- *
287
- * The method automatically checks for duplicate items within the transaction
288
- * to prevent multiple operations on the same item.
289
- *
290
- * @example
291
- * ```typescript
292
- * // Simple put operation
293
- * transaction.put('orders', {
294
- * orderId: '123',
295
- * status: 'PENDING',
296
- * amount: 100
297
- * });
298
- *
299
- * // Conditional put operation
300
- * transaction.put(
301
- * 'inventory',
302
- * { productId: 'ABC', quantity: 50 },
303
- * op => op.attributeNotExists('productId')
304
- * );
305
- *
306
- * // Put with complex condition
307
- * transaction.put(
308
- * 'users',
309
- * { userId: '123', status: 'ACTIVE' },
310
- * op => op.and([
311
- * op.attributeNotExists('userId'),
312
- * op.beginsWith('status', 'ACTIVE')
313
- * ])
314
- * );
315
- * ```
316
- *
317
- * @param tableName - The name of the DynamoDB table
318
- * @param item - The item to put into the table
319
- * @param condition - Optional condition that must be satisfied
320
- * @returns The transaction builder for method chaining
321
- * @throws {Error} If a duplicate item is detected in the transaction
322
- */
323
- put(tableName, item, condition) {
324
- this.checkForDuplicateItem(tableName, item);
325
- const transactionItem = {
326
- type: "Put",
327
- params: {
328
- tableName,
329
- item
330
- }
331
- };
332
- if (condition) {
333
- const { expression, names, values } = prepareExpressionParams(condition);
334
- transactionItem.params.conditionExpression = expression;
335
- transactionItem.params.expressionAttributeNames = names;
336
- transactionItem.params.expressionAttributeValues = values;
337
- }
338
- this.items.push(transactionItem);
339
- return this;
340
- }
341
- /**
342
- * Adds a pre-configured put operation to the transaction.
343
- * Use this method when you need to:
344
- * - Reuse put commands from PutBuilder
345
- * - Add complex put operations with pre-configured parameters
346
- * - Integrate with existing put command configurations
347
- *
348
- * This method is particularly useful when working with PutBuilder
349
- * to maintain consistency in put operations across your application.
350
- *
351
- * @example
352
- * ```typescript
353
- * // Create a put command with PutBuilder
354
- * const putCommand = new PutBuilder(executor, newItem, 'users')
355
- * .condition(op => op.attributeNotExists('userId'))
356
- * .toDynamoCommand();
357
- *
358
- * // Add the command to the transaction
359
- * transaction.putWithCommand(putCommand);
360
- * ```
361
- *
362
- * @param command - The complete put command configuration
363
- * @returns The transaction builder for method chaining
364
- * @throws {Error} If a duplicate item is detected in the transaction
365
- * @see PutBuilder for creating put commands
366
- */
367
- putWithCommand(command) {
368
- this.checkForDuplicateItem(command.tableName, command.item);
369
- const transactionItem = {
370
- type: "Put",
371
- params: command
372
- };
373
- this.items.push(transactionItem);
374
- return this;
375
- }
376
- /**
377
- * Adds a delete operation to the transaction.
378
- * Use this method when you need to:
379
- * - Remove items as part of a transaction
380
- * - Conditionally delete items
381
- * - Ensure items exist before deletion
382
- *
383
- * The method automatically checks for duplicate items within the transaction
384
- * to prevent multiple operations on the same item.
385
- *
386
- * @example
387
- * ```typescript
388
- * // Simple delete operation
389
- * transaction.delete('orders', {
390
- * pk: 'ORDER#123',
391
- * sk: 'METADATA'
392
- * });
393
- *
394
- * // Conditional delete operation
395
- * transaction.delete(
396
- * 'users',
397
- * { pk: 'USER#123' },
398
- * op => op.eq('status', 'INACTIVE')
399
- * );
400
- *
401
- * // Delete with complex condition
402
- * transaction.delete(
403
- * 'products',
404
- * { pk: 'PROD#ABC' },
405
- * op => op.and([
406
- * op.eq('status', 'DRAFT'),
407
- * op.lt('version', 5)
408
- * ])
409
- * );
410
- * ```
411
- *
412
- * @param tableName - The name of the DynamoDB table
413
- * @param key - The primary key of the item to delete
414
- * @param condition - Optional condition that must be satisfied
415
- * @returns The transaction builder for method chaining
416
- * @throws {Error} If a duplicate item is detected in the transaction
417
- */
418
- delete(tableName, key, condition) {
419
- const keyCondition = this.createKeyForPrimaryIndex(key);
420
- this.checkForDuplicateItem(tableName, keyCondition);
421
- const transactionItem = {
422
- type: "Delete",
423
- params: {
424
- tableName,
425
- key: keyCondition
426
- }
427
- };
428
- if (condition) {
429
- const { expression, names, values } = prepareExpressionParams(condition);
430
- transactionItem.params.conditionExpression = expression;
431
- transactionItem.params.expressionAttributeNames = names;
432
- transactionItem.params.expressionAttributeValues = values;
433
- }
434
- this.items.push(transactionItem);
435
- return this;
436
- }
437
- /**
438
- * Adds a pre-configured delete operation to the transaction.
439
- * Use this method when you need to:
440
- * - Reuse delete commands from DeleteBuilder
441
- * - Add complex delete operations with pre-configured parameters
442
- * - Integrate with existing delete command configurations
443
- *
444
- * This method is particularly useful when working with DeleteBuilder
445
- * to maintain consistency in delete operations across your application.
446
- *
447
- * @example
448
- * ```typescript
449
- * // Create a delete command with DeleteBuilder
450
- * const deleteCommand = new DeleteBuilder(executor, 'users', { pk: 'USER#123' })
451
- * .condition(op => op.and([
452
- * op.attributeExists('pk'),
453
- * op.eq('status', 'INACTIVE')
454
- * ]))
455
- * .toDynamoCommand();
456
- *
457
- * // Add the command to the transaction
458
- * transaction.deleteWithCommand(deleteCommand);
459
- * ```
460
- *
461
- * @param command - The complete delete command configuration
462
- * @returns The transaction builder for method chaining
463
- * @throws {Error} If a duplicate item is detected in the transaction
464
- * @see DeleteBuilder for creating delete commands
465
- */
466
- deleteWithCommand(command) {
467
- const keyCondition = this.createKeyForPrimaryIndex(command.key);
468
- this.checkForDuplicateItem(command.tableName, keyCondition);
469
- const transactionItem = {
470
- type: "Delete",
471
- params: {
472
- ...command,
473
- key: keyCondition
474
- }
475
- };
476
- this.items.push(transactionItem);
477
- return this;
478
- }
479
- /**
480
- * Adds an update operation to the transaction.
481
- * Use this method when you need to:
482
- * - Modify existing items as part of a transaction
483
- * - Update multiple attributes atomically
484
- * - Apply conditional updates
485
- * - Perform complex attribute manipulations
486
- *
487
- * The method supports all DynamoDB update expressions:
488
- * - SET: Modify or add attributes
489
- * - REMOVE: Delete attributes
490
- * - ADD: Update numbers and sets
491
- * - DELETE: Remove elements from a set
492
- *
493
- * @example
494
- * ```typescript
495
- * // Simple update
496
- * transaction.update(
497
- * 'orders',
498
- * { pk: 'ORDER#123' },
499
- * 'SET #status = :status',
500
- * { '#status': 'status' },
501
- * { ':status': 'PROCESSING' }
502
- * );
503
- *
504
- * // Complex update with multiple operations
505
- * transaction.update(
506
- * 'products',
507
- * { pk: 'PROD#ABC' },
508
- * 'SET #qty = #qty - :amount, #status = :status REMOVE #oldAttr',
509
- * { '#qty': 'quantity', '#status': 'status', '#oldAttr': 'deprecated_field' },
510
- * { ':amount': 1, ':status': 'LOW_STOCK' }
511
- * );
512
- *
513
- * // Conditional update
514
- * transaction.update(
515
- * 'users',
516
- * { pk: 'USER#123' },
517
- * 'SET #lastLogin = :now',
518
- * { '#lastLogin': 'lastLoginDate' },
519
- * { ':now': new Date().toISOString() },
520
- * op => op.attributeExists('pk')
521
- * );
522
- * ```
523
- *
524
- * @param tableName - The name of the DynamoDB table
525
- * @param key - The primary key of the item to update
526
- * @param updateExpression - The update expression (SET, REMOVE, ADD, DELETE)
527
- * @param expressionAttributeNames - Map of attribute name placeholders to actual names
528
- * @param expressionAttributeValues - Map of value placeholders to actual values
529
- * @param condition - Optional condition that must be satisfied
530
- * @returns The transaction builder for method chaining
531
- * @throws {Error} If a duplicate item is detected in the transaction
532
- */
533
- update(tableName, key, updateExpression, expressionAttributeNames, expressionAttributeValues, condition) {
534
- const keyCondition = this.createKeyForPrimaryIndex(key);
535
- this.checkForDuplicateItem(tableName, keyCondition);
536
- const transactionItem = {
537
- type: "Update",
538
- params: {
539
- tableName,
540
- key: keyCondition,
541
- updateExpression,
542
- expressionAttributeNames,
543
- expressionAttributeValues
544
- }
545
- };
546
- if (condition) {
547
- const { expression, names, values } = prepareExpressionParams(condition);
548
- transactionItem.params.conditionExpression = expression;
549
- transactionItem.params.expressionAttributeNames = {
550
- ...transactionItem.params.expressionAttributeNames,
551
- ...names
552
- };
553
- transactionItem.params.expressionAttributeValues = {
554
- ...transactionItem.params.expressionAttributeValues,
555
- ...values
556
- };
557
- }
558
- this.items.push(transactionItem);
559
- return this;
560
- }
561
- /**
562
- * Adds a pre-configured update operation to the transaction.
563
- * Use this method when you need to:
564
- * - Reuse update commands from UpdateBuilder
565
- * - Add complex update operations with pre-configured parameters
566
- * - Integrate with existing update command configurations
567
- *
568
- * This method is particularly useful when working with UpdateBuilder
569
- * to maintain consistency in update operations across your application.
570
- *
571
- * @example
572
- * ```typescript
573
- * // Create an update command with UpdateBuilder
574
- * const updateCommand = new UpdateBuilder(executor, 'inventory', { pk: 'PROD#ABC' })
575
- * .set('quantity', ':qty')
576
- * .set('lastUpdated', ':now')
577
- * .values({
578
- * ':qty': 100,
579
- * ':now': new Date().toISOString()
580
- * })
581
- * .condition(op => op.gt('quantity', 0))
582
- * .toDynamoCommand();
583
- *
584
- * // Add the command to the transaction
585
- * transaction.updateWithCommand(updateCommand);
586
- * ```
587
- *
588
- * @param command - The complete update command configuration
589
- * @returns The transaction builder for method chaining
590
- * @throws {Error} If a duplicate item is detected in the transaction
591
- * @see UpdateBuilder for creating update commands
592
- */
593
- updateWithCommand(command) {
594
- const keyCondition = this.createKeyForPrimaryIndex(command.key);
595
- this.checkForDuplicateItem(command.tableName, keyCondition);
596
- const transactionItem = {
597
- type: "Update",
598
- params: {
599
- ...command,
600
- key: keyCondition
601
- }
602
- };
603
- this.items.push(transactionItem);
604
- return this;
605
- }
606
- /**
607
- * Adds a condition check operation to the transaction.
608
- * Use this method when you need to:
609
- * - Validate item state without modifying it
610
- * - Ensure data consistency across tables
611
- * - Implement complex business rules
612
- * - Verify preconditions for other operations
613
- *
614
- * Condition checks are particularly useful for:
615
- * - Implementing optimistic locking
616
- * - Ensuring referential integrity
617
- * - Validating business rules atomically
618
- *
619
- * @example
620
- * ```typescript
621
- * // Check if order is in correct state
622
- * transaction.conditionCheck(
623
- * 'orders',
624
- * { pk: 'ORDER#123' },
625
- * op => op.eq('status', 'PENDING')
626
- * );
627
- *
628
- * // Complex condition check
629
- * transaction.conditionCheck(
630
- * 'inventory',
631
- * { pk: 'PROD#ABC' },
632
- * op => op.and([
633
- * op.gt('quantity', 0),
634
- * op.eq('status', 'ACTIVE'),
635
- * op.attributeExists('lastRestockDate')
636
- * ])
637
- * );
638
- *
639
- * // Check with multiple attributes
640
- * transaction.conditionCheck(
641
- * 'users',
642
- * { pk: 'USER#123' },
643
- * op => op.or([
644
- * op.eq('status', 'PREMIUM'),
645
- * op.gte('credits', 100)
646
- * ])
647
- * );
648
- * ```
649
- *
650
- * @param tableName - The name of the DynamoDB table
651
- * @param key - The primary key of the item to check
652
- * @param condition - The condition that must be satisfied
653
- * @returns The transaction builder for method chaining
654
- * @throws {Error} If a duplicate item is detected in the transaction
655
- * @throws {Error} If condition expression generation fails
656
- */
657
- conditionCheck(tableName, key, condition) {
658
- const keyCondition = this.createKeyForPrimaryIndex(key);
659
- this.checkForDuplicateItem(tableName, keyCondition);
660
- const { expression, names, values } = prepareExpressionParams(condition);
661
- if (!expression) {
662
- throw new Error("Failed to generate condition expression");
663
- }
664
- const transactionItem = {
665
- type: "ConditionCheck",
666
- params: {
667
- tableName,
668
- key: keyCondition,
669
- conditionExpression: expression,
670
- expressionAttributeNames: names,
671
- expressionAttributeValues: values
672
- }
673
- };
674
- this.items.push(transactionItem);
675
- return this;
676
- }
677
- /**
678
- * Adds a pre-configured condition check operation to the transaction.
679
- * Use this method when you need to:
680
- * - Reuse condition checks from ConditionCheckBuilder
681
- * - Add complex condition checks with pre-configured parameters
682
- * - Integrate with existing condition check configurations
683
- *
684
- * This method is particularly useful when working with ConditionCheckBuilder
685
- * to maintain consistency in condition checks across your application.
686
- *
687
- * @example
688
- * ```typescript
689
- * // Create a condition check with ConditionCheckBuilder
690
- * const checkCommand = new ConditionCheckBuilder('inventory', { pk: 'PROD#ABC' })
691
- * .condition(op => op.and([
692
- * op.between('quantity', 10, 100),
693
- * op.beginsWith('category', 'ELECTRONICS'),
694
- * op.attributeExists('lastAuditDate')
695
- * ]))
696
- * .toDynamoCommand();
697
- *
698
- * // Add the command to the transaction
699
- * transaction.conditionCheckWithCommand(checkCommand);
700
- * ```
701
- *
702
- * @param command - The complete condition check command configuration
703
- * @returns The transaction builder for method chaining
704
- * @throws {Error} If a duplicate item is detected in the transaction
705
- * @see ConditionCheckBuilder for creating condition check commands
706
- */
707
- conditionCheckWithCommand(command) {
708
- const keyCondition = this.createKeyForPrimaryIndex(command.key);
709
- this.checkForDuplicateItem(command.tableName, keyCondition);
710
- const transactionItem = {
711
- type: "ConditionCheck",
712
- params: {
713
- ...command,
714
- key: keyCondition
715
- }
716
- };
717
- this.items.push(transactionItem);
718
- return this;
719
- }
720
- /**
721
- * Sets options for the transaction execution.
722
- * Use this method when you need to:
723
- * - Enable idempotent transactions
724
- * - Track consumed capacity
725
- * - Monitor item collection metrics
726
- *
727
- * @example
728
- * ```typescript
729
- * // Enable idempotency and capacity tracking
730
- * transaction.withOptions({
731
- * clientRequestToken: 'unique-request-id-123',
732
- * returnConsumedCapacity: 'TOTAL'
733
- * });
734
- *
735
- * // Track item collection metrics
736
- * transaction.withOptions({
737
- * returnItemCollectionMetrics: 'SIZE'
738
- * });
739
- * ```
740
- *
741
- * Note: ClientRequestToken can be used to make transactions idempotent,
742
- * ensuring the same transaction is not executed multiple times.
743
- *
744
- * @param options - Configuration options for the transaction
745
- * @returns The transaction builder for method chaining
746
- */
747
- withOptions(options) {
748
- this.options = { ...this.options, ...options };
749
- return this;
750
- }
751
- /**
752
- * Gets a human-readable representation of the transaction items.
753
- * Use this method when you need to:
754
- * - Debug complex transactions
755
- * - Verify operation parameters
756
- * - Log transaction details
757
- * - Troubleshoot condition expressions
758
- *
759
- * The method resolves all expression placeholders with their actual values,
760
- * making it easier to understand the transaction's operations.
761
- *
762
- * @example
763
- * ```typescript
764
- * // Add multiple operations
765
- * transaction
766
- * .put('orders', { orderId: '123', status: 'PENDING' })
767
- * .update('inventory',
768
- * { productId: 'ABC' },
769
- * 'SET quantity = quantity - :amount',
770
- * undefined,
771
- * { ':amount': 1 }
772
- * );
773
- *
774
- * // Debug the transaction
775
- * const debugInfo = transaction.debug();
776
- * console.log('Transaction operations:', debugInfo);
777
- * ```
778
- *
779
- * @returns An array of readable representations of the transaction items
780
- */
781
- debug() {
782
- return debugTransaction(this.items);
783
- }
784
- /**
785
- * Executes all operations in the transaction atomically.
786
- * Use this method when you need to:
787
- * - Perform multiple operations atomically
788
- * - Ensure all-or-nothing execution
789
- * - Maintain data consistency across operations
790
- *
791
- * The transaction will only succeed if all operations succeed.
792
- * If any operation fails, the entire transaction is rolled back.
793
- *
794
- * @example
795
- * ```typescript
796
- * try {
797
- * // Build and execute transaction
798
- * await transaction
799
- * .put('orders', newOrder)
800
- * .update('inventory',
801
- * { productId: 'ABC' },
802
- * 'SET quantity = quantity - :qty',
803
- * undefined,
804
- * { ':qty': 1 }
805
- * )
806
- * .conditionCheck('products',
807
- * { productId: 'ABC' },
808
- * op => op.eq('status', 'ACTIVE')
809
- * )
810
- * .execute();
811
- *
812
- * console.log('Transaction completed successfully');
813
- * } catch (error) {
814
- * // Handle transaction failure
815
- * console.error('Transaction failed:', error);
816
- * }
817
- * ```
818
- *
819
- * @throws {Error} If no transaction items are specified
820
- * @throws {Error} If any operation in the transaction fails
821
- * @returns A promise that resolves when the transaction completes
822
- */
823
- async execute() {
824
- if (this.items.length === 0) {
825
- throw new Error("No transaction items specified");
826
- }
827
- const transactItems = this.items.map((item) => {
828
- switch (item.type) {
829
- case "Put":
830
- return {
831
- Put: {
832
- TableName: item.params.tableName,
833
- Item: item.params.item,
834
- ConditionExpression: item.params.conditionExpression,
835
- ExpressionAttributeNames: item.params.expressionAttributeNames,
836
- ExpressionAttributeValues: item.params.expressionAttributeValues
837
- }
838
- };
839
- case "Delete":
840
- return {
841
- Delete: {
842
- TableName: item.params.tableName,
843
- Key: item.params.key,
844
- ConditionExpression: item.params.conditionExpression,
845
- ExpressionAttributeNames: item.params.expressionAttributeNames,
846
- ExpressionAttributeValues: item.params.expressionAttributeValues
847
- }
848
- };
849
- case "Update":
850
- return {
851
- Update: {
852
- TableName: item.params.tableName,
853
- Key: item.params.key,
854
- UpdateExpression: item.params.updateExpression,
855
- ConditionExpression: item.params.conditionExpression,
856
- ExpressionAttributeNames: item.params.expressionAttributeNames,
857
- ExpressionAttributeValues: item.params.expressionAttributeValues
858
- }
859
- };
860
- case "ConditionCheck":
861
- return {
862
- ConditionCheck: {
863
- TableName: item.params.tableName,
864
- Key: item.params.key,
865
- ConditionExpression: item.params.conditionExpression,
866
- ExpressionAttributeNames: item.params.expressionAttributeNames,
867
- ExpressionAttributeValues: item.params.expressionAttributeValues
868
- }
869
- };
870
- default: {
871
- const exhaustiveCheck = item;
872
- throw new Error(`Unsupported transaction item type: ${String(exhaustiveCheck)}`);
873
- }
874
- }
875
- });
876
- const params = {
877
- TransactItems: transactItems,
878
- ClientRequestToken: this.options.clientRequestToken,
879
- ReturnConsumedCapacity: this.options.returnConsumedCapacity,
880
- ReturnItemCollectionMetrics: this.options.returnItemCollectionMetrics
881
- };
882
- try {
883
- await this.executor(params);
884
- } catch (error) {
885
- console.log(this.debug());
886
- console.error("Error executing transaction:", error);
887
- throw error;
888
- }
889
- }
890
- };
891
-
892
- exports.TransactionBuilder = TransactionBuilder;
893
- //# sourceMappingURL=transaction-builder.cjs.map
894
- //# sourceMappingURL=transaction-builder.cjs.map