betterddb 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/betterddb.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  // src/dynamo-dal.ts
2
2
  import { z, ZodSchema } from 'zod';
3
3
  import { DynamoDB } from 'aws-sdk';
4
+ import { QueryBuilder } from './builders/query-builder';
5
+ import { ScanBuilder } from './builders/scan-builder';
6
+ import { UpdateBuilder } from './builders/update-builder';
7
+ import { CreateBuilder } from './builders/create-builder';
8
+ import { GetBuilder } from './builders/get-builder';
9
+ import { DeleteBuilder } from './builders/delete-builder';
4
10
 
5
11
  export type PrimaryKeyValue = string | number;
6
12
 
@@ -41,7 +47,11 @@ export interface SortKeyConfig<T> {
41
47
  * Configuration for a Global Secondary Index (GSI).
42
48
  */
43
49
  export interface GSIConfig<T> {
50
+ /** The name of the GSI in DynamoDB */
51
+ name: string;
52
+ /** The primary key configuration for the GSI */
44
53
  primary: PrimaryKeyConfig<T>;
54
+ /** The sort key configuration for the GSI, if any */
45
55
  sort?: SortKeyConfig<T>;
46
56
  }
47
57
 
@@ -62,6 +72,7 @@ export interface KeysConfig<T> {
62
72
  export interface BetterDDBOptions<T> {
63
73
  schema: ZodSchema<T>;
64
74
  tableName: string;
75
+ entityName: string;
65
76
  keys: KeysConfig<T>;
66
77
  client: DynamoDB.DocumentClient;
67
78
  /**
@@ -80,6 +91,7 @@ export interface BetterDDBOptions<T> {
80
91
  export class BetterDDB<T> {
81
92
  protected schema: ZodSchema<T>;
82
93
  protected tableName: string;
94
+ protected entityName: string;
83
95
  protected client: DynamoDB.DocumentClient;
84
96
  protected keys: KeysConfig<T>;
85
97
  protected autoTimestamps: boolean;
@@ -87,11 +99,33 @@ export class BetterDDB<T> {
87
99
  constructor(options: BetterDDBOptions<T>) {
88
100
  this.schema = options.schema;
89
101
  this.tableName = options.tableName;
102
+ this.entityName = options.entityName.toUpperCase();
90
103
  this.keys = options.keys;
91
104
  this.client = options.client;
92
105
  this.autoTimestamps = options.autoTimestamps ?? false;
93
106
  }
94
107
 
108
+ public getKeys(): KeysConfig<T> {
109
+ return this.keys;
110
+ }
111
+
112
+ public getTableName(): string {
113
+ return this.tableName;
114
+ }
115
+
116
+ public getClient(): DynamoDB.DocumentClient {
117
+ return this.client;
118
+ }
119
+
120
+
121
+ public getSchema(): ZodSchema<T> {
122
+ return this.schema;
123
+ }
124
+
125
+ public getAutoTimestamps(): boolean {
126
+ return this.autoTimestamps;
127
+ }
128
+
95
129
  // Helper: Retrieve the key value from a KeyDefinition.
96
130
  protected getKeyValue(def: KeyDefinition<T>, rawKey: Partial<T>): string {
97
131
  if (typeof def === 'string' || typeof def === 'number' || typeof def === 'symbol') {
@@ -104,7 +138,7 @@ export class BetterDDB<T> {
104
138
  /**
105
139
  * Build the primary key from a raw key object.
106
140
  */
107
- protected buildKey(rawKey: Partial<T>): Record<string, any> {
141
+ public buildKey(rawKey: Partial<T>): Record<string, any> {
108
142
  const keyObj: Record<string, any> = {};
109
143
 
110
144
  // For primary (partition) key:
@@ -132,7 +166,7 @@ export class BetterDDB<T> {
132
166
  /**
133
167
  * Build index attributes for each defined GSI.
134
168
  */
135
- protected buildIndexes(rawItem: Partial<T>): Record<string, any> {
169
+ public buildIndexes(rawItem: Partial<T>): Record<string, any> {
136
170
  const indexAttributes: Record<string, any> = {};
137
171
  if (this.keys.gsis) {
138
172
  for (const gsiName in this.keys.gsis) {
@@ -168,433 +202,42 @@ export class BetterDDB<T> {
168
202
  * - Optionally injects timestamps,
169
203
  * - Validates the item and writes it to DynamoDB.
170
204
  */
171
- async create(item: T): Promise<T> {
172
- if (this.autoTimestamps) {
173
- const now = new Date().toISOString();
174
- item = { ...item, createdAt: now, updatedAt: now } as T;
175
- }
176
-
177
- const validated = this.schema.parse(item);
178
- let finalItem = { ...validated };
179
-
180
- // Compute and merge primary key.
181
- const computedKeys = this.buildKey(validated);
182
- finalItem = { ...finalItem, ...computedKeys };
183
-
184
- // Compute and merge index attributes.
185
- const indexAttributes = this.buildIndexes(validated);
186
- finalItem = { ...finalItem, ...indexAttributes };
187
-
188
- try {
189
- await this.client.put({ TableName: this.tableName, Item: finalItem as DynamoDB.DocumentClient.PutItemInputAttributeMap }).promise();
190
- return validated;
191
- } catch (error) {
192
- console.error('Error during create operation:', error);
193
- throw error;
194
- }
195
- }
196
-
197
- async get(rawKey: Partial<T>): Promise<T | null> {
198
- const Key = this.buildKey(rawKey);
199
- try {
200
- const result = await this.client.get({ TableName: this.tableName, Key }).promise();
201
- if (!result.Item) return null;
202
- return this.schema.parse(result.Item);
203
- } catch (error) {
204
- console.error('Error during get operation:', error);
205
- throw error;
206
- }
207
- }
208
-
209
- async update(
210
- rawKey: Partial<T>,
211
- update: Partial<T>,
212
- options?: { expectedVersion?: number }
213
- ): Promise<T> {
214
- const ExpressionAttributeNames: Record<string, string> = {};
215
- const ExpressionAttributeValues: Record<string, any> = {};
216
- const UpdateExpressionParts: string[] = [];
217
- const ConditionExpressionParts: string[] = [];
218
-
219
- // Exclude key fields from update.
220
- const keyFieldNames = [
221
- this.keys.primary.name,
222
- this.keys.sort ? this.keys.sort.name : undefined
223
- ].filter(Boolean) as string[];
224
-
225
- for (const [attr, value] of Object.entries(update)) {
226
- if (keyFieldNames.includes(attr)) continue;
227
- const attributeKey = `#${attr}`;
228
- const valueKey = `:${attr}`;
229
- ExpressionAttributeNames[attributeKey] = attr;
230
- ExpressionAttributeValues[valueKey] = value;
231
- UpdateExpressionParts.push(`${attributeKey} = ${valueKey}`);
232
- }
233
-
234
- if (this.autoTimestamps) {
235
- const now = new Date().toISOString();
236
- ExpressionAttributeNames['#updatedAt'] = 'updatedAt';
237
- ExpressionAttributeValues[':updatedAt'] = now;
238
- UpdateExpressionParts.push('#updatedAt = :updatedAt');
239
- }
240
-
241
- if (options?.expectedVersion !== undefined) {
242
- ExpressionAttributeNames['#version'] = 'version';
243
- ExpressionAttributeValues[':expectedVersion'] = options.expectedVersion;
244
- ExpressionAttributeValues[':newVersion'] = options.expectedVersion + 1;
245
- UpdateExpressionParts.push('#version = :newVersion');
246
- ConditionExpressionParts.push('#version = :expectedVersion');
247
- }
248
-
249
- if (UpdateExpressionParts.length === 0) {
250
- throw new Error('No attributes provided to update');
251
- }
252
-
253
- const UpdateExpression = 'SET ' + UpdateExpressionParts.join(', ');
254
- const params: DynamoDB.DocumentClient.UpdateItemInput = {
255
- TableName: this.tableName,
256
- Key: this.buildKey(rawKey),
257
- UpdateExpression,
258
- ExpressionAttributeNames,
259
- ExpressionAttributeValues,
260
- ReturnValues: 'ALL_NEW'
261
- };
262
-
263
- if (ConditionExpressionParts.length > 0) {
264
- params.ConditionExpression = ConditionExpressionParts.join(' AND ');
265
- }
266
-
267
- try {
268
- const result = await this.client.update(params).promise();
269
- if (!result.Attributes) {
270
- throw new Error('No attributes returned after update');
271
- }
272
- return this.schema.parse(result.Attributes);
273
- } catch (error) {
274
- console.error('Error during update operation:', error);
275
- throw error;
276
- }
277
- }
278
-
279
- async delete(rawKey: Partial<T>): Promise<void> {
280
- const Key = this.buildKey(rawKey);
281
- try {
282
- await this.client.delete({ TableName: this.tableName, Key }).promise();
283
- } catch (error) {
284
- console.error('Error during delete operation:', error);
285
- throw error;
286
- }
287
- }
288
-
289
- async queryByGsi(
290
- gsiName: string,
291
- key: Partial<T>,
292
- sortKeyCondition?: { operator: 'eq' | 'begins_with' | 'between'; values: any | [any, any] }
293
- ): Promise<T[]> {
294
- if (!this.keys.gsis || !this.keys.gsis[gsiName]) {
295
- throw new Error(`GSI "${gsiName}" is not configured`);
296
- }
297
- const indexConfig = this.keys.gsis[gsiName];
298
- const ExpressionAttributeNames: Record<string, string> = {
299
- [`#${indexConfig.primary.name}`]: indexConfig.primary.name
300
- };
301
- const ExpressionAttributeValues: Record<string, any> = {
302
- [`:${indexConfig.primary.name}`]:
303
- (typeof indexConfig.primary.definition === 'string' ||
304
- typeof indexConfig.primary.definition === 'number' ||
305
- typeof indexConfig.primary.definition === 'symbol')
306
- ? String((key as any)[indexConfig.primary.definition])
307
- : indexConfig.primary.definition.build(key)
308
- };
309
- let KeyConditionExpression = `#${indexConfig.primary.name} = :${indexConfig.primary.name}`;
310
-
311
- if (indexConfig.sort && sortKeyCondition) {
312
- const skFieldName = indexConfig.sort.name;
313
- ExpressionAttributeNames['#gsiSk'] = skFieldName;
314
- switch (sortKeyCondition.operator) {
315
- case 'eq':
316
- ExpressionAttributeValues[':gsiSk'] = sortKeyCondition.values;
317
- KeyConditionExpression += ' AND #gsiSk = :gsiSk';
318
- break;
319
- case 'begins_with':
320
- ExpressionAttributeValues[':gsiSk'] = sortKeyCondition.values;
321
- KeyConditionExpression += ' AND begins_with(#gsiSk, :gsiSk)';
322
- break;
323
- case 'between':
324
- if (!Array.isArray(sortKeyCondition.values) || sortKeyCondition.values.length !== 2) {
325
- throw new Error("For 'between' operator, values must be a tuple of two items");
326
- }
327
- ExpressionAttributeValues[':gsiSkStart'] = sortKeyCondition.values[0];
328
- ExpressionAttributeValues[':gsiSkEnd'] = sortKeyCondition.values[1];
329
- KeyConditionExpression += ' AND #gsiSk BETWEEN :gsiSkStart AND :gsiSkEnd';
330
- break;
331
- default:
332
- throw new Error(`Unsupported sort key operator: ${sortKeyCondition.operator}`);
333
- }
334
- }
335
- try {
336
- const result = await this.client
337
- .query({
338
- TableName: this.tableName,
339
- IndexName: gsiName,
340
- KeyConditionExpression,
341
- ExpressionAttributeNames,
342
- ExpressionAttributeValues
343
- })
344
- .promise();
345
- return (result.Items || []).map(item => this.schema.parse(item));
346
- } catch (error) {
347
- console.error('Error during queryByGsi operation:', error);
348
- throw error;
349
- }
205
+ public create(item: T): CreateBuilder<T> {
206
+ return new CreateBuilder<T>(this, item);
350
207
  }
351
208
 
352
209
  /**
353
- * Query by primary key (using the computed primary key) and an optional sort key condition.
210
+ * Get an item by its primary key.
354
211
  */
355
- async queryByPrimaryKey(
356
- rawKey: Partial<T>,
357
- sortKeyCondition?: { operator: 'eq' | 'begins_with' | 'between'; values: any | [any, any] },
358
- options?: { limit?: number; lastKey?: Record<string, any> }
359
- ): Promise<{ items: T[]; lastKey?: Record<string, any> }> {
360
- const pkAttrName = this.keys.primary.name;
361
- const pkValue =
362
- (typeof this.keys.primary.definition === 'string' ||
363
- typeof this.keys.primary.definition === 'number' ||
364
- typeof this.keys.primary.definition === 'symbol')
365
- ? String((rawKey as any)[this.keys.primary.definition])
366
- : this.keys.primary.definition.build(rawKey);
367
-
368
- const ExpressionAttributeNames: Record<string, string> = {
369
- [`#${pkAttrName}`]: pkAttrName
370
- };
371
- const ExpressionAttributeValues: Record<string, any> = {
372
- [`:${pkAttrName}`]: pkValue
373
- };
374
-
375
- let KeyConditionExpression = `#${pkAttrName} = :${pkAttrName}`;
376
-
377
- if (this.keys.sort && sortKeyCondition) {
378
- const skAttrName = this.keys.sort.name;
379
- ExpressionAttributeNames[`#${skAttrName}`] = skAttrName;
380
- switch (sortKeyCondition.operator) {
381
- case 'eq':
382
- ExpressionAttributeValues[':skValue'] = sortKeyCondition.values;
383
- KeyConditionExpression += ` AND #${skAttrName} = :skValue`;
384
- break;
385
- case 'begins_with':
386
- ExpressionAttributeValues[':skValue'] = sortKeyCondition.values;
387
- KeyConditionExpression += ` AND begins_with(#${skAttrName}, :skValue)`;
388
- break;
389
- case 'between':
390
- if (!Array.isArray(sortKeyCondition.values) || sortKeyCondition.values.length !== 2) {
391
- throw new Error("For 'between' operator, values must be a tuple of two items");
392
- }
393
- ExpressionAttributeValues[':skStart'] = sortKeyCondition.values[0];
394
- ExpressionAttributeValues[':skEnd'] = sortKeyCondition.values[1];
395
- KeyConditionExpression += ` AND #${skAttrName} BETWEEN :skStart AND :skEnd`;
396
- break;
397
- default:
398
- throw new Error(`Unsupported sort key operator: ${sortKeyCondition.operator}`);
399
- }
400
- }
401
-
402
- const queryParams: DynamoDB.DocumentClient.QueryInput = {
403
- TableName: this.tableName,
404
- KeyConditionExpression,
405
- ExpressionAttributeNames,
406
- ExpressionAttributeValues
407
- };
408
-
409
- if (options?.limit) {
410
- queryParams.Limit = options.limit;
411
- }
412
- if (options?.lastKey) {
413
- queryParams.ExclusiveStartKey = options.lastKey;
414
- }
415
-
416
- const result = await this.client.query(queryParams).promise();
417
- const items = (result.Items || []).map(item => this.schema.parse(item));
418
- return { items, lastKey: result.LastEvaluatedKey };
419
- }
420
-
421
- // ───── Transaction Helpers ─────────────────────────────
422
-
423
- buildTransactPut(item: T): DynamoDB.DocumentClient.TransactWriteItem {
424
- const computedKeys = this.buildKey(item);
425
- const indexAttributes = this.buildIndexes(item);
426
- const finalItem = { ...item, ...computedKeys, ...indexAttributes };
427
- const validated = this.schema.parse(finalItem);
428
- return {
429
- Put: {
430
- TableName: this.tableName,
431
- Item: validated as DynamoDB.DocumentClient.PutItemInputAttributeMap
432
- }
433
- };
434
- }
435
-
436
- buildTransactUpdate(
437
- rawKey: Partial<T>,
438
- update: Partial<T>,
439
- options?: { expectedVersion?: number }
440
- ): DynamoDB.DocumentClient.TransactWriteItem {
441
- const ExpressionAttributeNames: Record<string, string> = {};
442
- const ExpressionAttributeValues: Record<string, any> = {};
443
- const UpdateExpressionParts: string[] = [];
444
- const ConditionExpressionParts: string[] = [];
445
-
446
- const keyFieldNames = [
447
- this.keys.primary.name,
448
- this.keys.sort ? this.keys.sort.name : undefined
449
- ].filter(Boolean) as string[];
450
-
451
- for (const [attr, value] of Object.entries(update)) {
452
- if (keyFieldNames.includes(attr)) continue;
453
- const attributeKey = `#${attr}`;
454
- const valueKey = `:${attr}`;
455
- ExpressionAttributeNames[attributeKey] = attr;
456
- ExpressionAttributeValues[valueKey] = value;
457
- UpdateExpressionParts.push(`${attributeKey} = ${valueKey}`);
458
- }
459
-
460
- if (this.autoTimestamps) {
461
- const now = new Date().toISOString();
462
- ExpressionAttributeNames['#updatedAt'] = 'updatedAt';
463
- ExpressionAttributeValues[':updatedAt'] = now;
464
- UpdateExpressionParts.push('#updatedAt = :updatedAt');
465
- }
466
-
467
- if (options?.expectedVersion !== undefined) {
468
- ExpressionAttributeNames['#version'] = 'version';
469
- ExpressionAttributeValues[':expectedVersion'] = options.expectedVersion;
470
- ExpressionAttributeValues[':newVersion'] = options.expectedVersion + 1;
471
- UpdateExpressionParts.push('#version = :newVersion');
472
- ConditionExpressionParts.push('#version = :expectedVersion');
473
- }
474
-
475
- if (UpdateExpressionParts.length === 0) {
476
- throw new Error('No attributes provided to update in transactUpdate');
477
- }
478
-
479
- const UpdateExpression = 'SET ' + UpdateExpressionParts.join(', ');
480
- const updateItem: DynamoDB.DocumentClient.Update = {
481
- TableName: this.tableName,
482
- Key: this.buildKey(rawKey),
483
- UpdateExpression,
484
- ExpressionAttributeNames,
485
- ExpressionAttributeValues
486
- };
487
- if (ConditionExpressionParts.length > 0) {
488
- updateItem.ConditionExpression = ConditionExpressionParts.join(' AND ');
489
- }
490
- return { Update: updateItem };
491
- }
492
-
493
- buildTransactDelete(rawKey: Partial<T>): DynamoDB.DocumentClient.TransactWriteItem {
494
- return {
495
- Delete: {
496
- TableName: this.tableName,
497
- Key: this.buildKey(rawKey)
498
- }
499
- };
500
- }
501
-
502
- async transactWrite(
503
- operations: DynamoDB.DocumentClient.TransactWriteItemList
504
- ): Promise<void> {
505
- try {
506
- await this.client.transactWrite({ TransactItems: operations }).promise();
507
- } catch (error) {
508
- console.error('Error during transactWrite operation:', error);
509
- throw error;
510
- }
511
- }
512
-
513
- async transactGetByKeys(rawKeys: Partial<T>[]): Promise<T[]> {
514
- const getItems = rawKeys.map(key => ({ TableName: this.tableName, Key: this.buildKey(key) }));
515
- return this.transactGet(getItems);
516
- }
517
-
518
- async transactGet(
519
- getItems: { TableName: string; Key: any }[]
520
- ): Promise<T[]> {
521
- try {
522
- const response = await this.client
523
- .transactGet({
524
- TransactItems: getItems.map(item => ({ Get: item }))
525
- })
526
- .promise();
527
- return (response.Responses || [])
528
- .filter(r => r.Item)
529
- .map(r => this.schema.parse(r.Item));
530
- } catch (error) {
531
- console.error('Error during transactGet operation:', error);
532
- throw error;
533
- }
212
+ public get(rawKey: Partial<T>): GetBuilder<T> {
213
+ return new GetBuilder<T>(this, rawKey);
534
214
  }
535
-
536
- // ───── Batch Write Support ─────────────────────────────
537
-
538
- async batchWrite(ops: { puts?: T[]; deletes?: Partial<T>[] }): Promise<void> {
539
- const putRequests = (ops.puts || []).map(item => {
540
- const computedKeys = this.buildKey(item);
541
- const indexAttributes = this.buildIndexes(item);
542
- const finalItem = { ...item, ...computedKeys, ...indexAttributes };
543
- const validated = this.schema.parse(finalItem);
544
- return { PutRequest: { Item: validated } };
545
- });
546
-
547
- const deleteRequests = (ops.deletes || []).map(rawKey => {
548
- const key = this.buildKey(rawKey);
549
- return { DeleteRequest: { Key: key } };
550
- });
551
-
552
- const allRequests = [...putRequests, ...deleteRequests];
553
-
554
- for (let i = 0; i < allRequests.length; i += 25) {
555
- const chunk = allRequests.slice(i, i + 25);
556
- let unprocessed = await this.batchWriteChunk(chunk as DynamoDB.DocumentClient.WriteRequest[]);
557
- while (unprocessed && Object.keys(unprocessed).length > 0) {
558
- await new Promise(resolve => setTimeout(resolve, 1000));
559
- unprocessed = await this.retryBatchWrite(unprocessed);
560
- }
561
- }
215
+
216
+ /**
217
+ * Update an item.
218
+ */
219
+ public update(key: Partial<T>, expectedVersion?: number): UpdateBuilder<T> {
220
+ return new UpdateBuilder<T>(this, key, expectedVersion);
562
221
  }
563
-
564
- private async batchWriteChunk(chunk: DynamoDB.DocumentClient.WriteRequest[]): Promise<DynamoDB.DocumentClient.BatchWriteItemOutput['UnprocessedItems']> {
565
- const params = {
566
- RequestItems: {
567
- [this.tableName]: chunk
568
- }
569
- };
570
- const result = await this.client.batchWrite(params as DynamoDB.DocumentClient.BatchWriteItemInput).promise();
571
- return result.UnprocessedItems;
222
+
223
+ /**
224
+ * Delete an item.
225
+ */
226
+ public delete(rawKey: Partial<T>): DeleteBuilder<T> {
227
+ return new DeleteBuilder<T>(this, rawKey);
572
228
  }
573
-
574
- private async retryBatchWrite(unprocessed: DynamoDB.DocumentClient.BatchWriteItemOutput['UnprocessedItems']): Promise<DynamoDB.DocumentClient.BatchWriteItemOutput['UnprocessedItems']> {
575
- const params = { RequestItems: unprocessed };
576
- const result = await this.client.batchWrite(params as DynamoDB.DocumentClient.BatchWriteItemInput).promise();
577
- return result.UnprocessedItems;
229
+
230
+ /**
231
+ * Query items.
232
+ */
233
+ public query(key: Partial<T>): QueryBuilder<T> {
234
+ return new QueryBuilder<T>(this, key);
578
235
  }
579
-
580
- // ───── Batch Get Support ─────────────────────────────
581
-
582
- async batchGet(rawKeys: Partial<T>[]): Promise<T[]> {
583
- const keys = rawKeys.map(key => this.buildKey(key));
584
- const results: T[] = [];
585
- for (let i = 0; i < keys.length; i += 100) {
586
- const chunk = keys.slice(i, i + 100);
587
- const params = {
588
- RequestItems: {
589
- [this.tableName]: {
590
- Keys: chunk
591
- }
592
- }
593
- };
594
- const result = await this.client.batchGet(params).promise();
595
- const items = result.Responses ? result.Responses[this.tableName] : [];
596
- results.push(...items.map(item => this.schema.parse(item)));
597
- }
598
- return results;
236
+
237
+ /**
238
+ * Scan for items.
239
+ */
240
+ public scan(): ScanBuilder<T> {
241
+ return new ScanBuilder<T>(this);
599
242
  }
600
243
  }
@@ -0,0 +1,82 @@
1
+ import { DynamoDB } from 'aws-sdk';
2
+ import { BetterDDB } from '../betterddb';
3
+
4
+ export class CreateBuilder<T> {
5
+ private extraTransactItems: DynamoDB.DocumentClient.TransactWriteItemList = [];
6
+
7
+ constructor(private parent: BetterDDB<T>, private item: T) {}
8
+
9
+ public async execute(): Promise<T> {
10
+ if (this.extraTransactItems.length > 0) {
11
+ // Build our update transaction item.
12
+ const myTransactItem = this.toTransactPut();
13
+ // Combine with extra transaction items.
14
+ const allItems = [...this.extraTransactItems, myTransactItem];
15
+ await this.parent.getClient().transactWrite({
16
+ TransactItems: allItems
17
+ }).promise();
18
+ // After transaction, retrieve the updated item.
19
+ const result = await this.parent.get(this.item).execute();
20
+ if (result === null) {
21
+ throw new Error('Item not found after transaction create');
22
+ }
23
+ return result;
24
+ } else {
25
+ let item = this.item;
26
+ if (this.parent.getAutoTimestamps()) {
27
+ const now = new Date().toISOString();
28
+ item = { ...item, createdAt: now, updatedAt: now } as T;
29
+ }
30
+ // Validate the item using the schema.
31
+ const validated = this.parent.getSchema().parse(item);
32
+ let finalItem = { ...validated };
33
+
34
+ // Compute and merge primary key.
35
+ const computedKeys = this.parent.buildKey(validated);
36
+ finalItem = { ...finalItem, ...computedKeys };
37
+
38
+ // Compute and merge index attributes.
39
+ const indexAttributes = this.parent.buildIndexes(validated);
40
+ finalItem = { ...finalItem, ...indexAttributes };
41
+
42
+ await this.parent.getClient().put({
43
+ TableName: this.parent.getTableName(),
44
+ Item: finalItem as DynamoDB.DocumentClient.PutItemInputAttributeMap
45
+ }).promise();
46
+
47
+ return validated;
48
+ }
49
+ }
50
+
51
+ public transactWrite(ops: DynamoDB.DocumentClient.TransactWriteItemList | DynamoDB.DocumentClient.TransactWriteItem): this {
52
+ if (Array.isArray(ops)) {
53
+ this.extraTransactItems.push(...ops);
54
+ } else {
55
+ this.extraTransactItems.push(ops);
56
+ }
57
+ return this;
58
+ }
59
+
60
+ public toTransactPut(): DynamoDB.DocumentClient.TransactWriteItem {
61
+ const putItem: DynamoDB.DocumentClient.Put = {
62
+ TableName: this.parent.getTableName(),
63
+ Item: this.item as DynamoDB.DocumentClient.PutItemInputAttributeMap,
64
+ };
65
+ return { Put: putItem };
66
+ }
67
+
68
+ public then<TResult1 = T, TResult2 = never>(
69
+ onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
70
+ onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
71
+ ): Promise<TResult1 | TResult2> {
72
+ return this.execute().then(onfulfilled, onrejected);
73
+ }
74
+ public catch<TResult = never>(
75
+ onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null
76
+ ): Promise<T | TResult> {
77
+ return this.execute().catch(onrejected);
78
+ }
79
+ public finally(onfinally?: (() => void) | null): Promise<T> {
80
+ return this.execute().finally(onfinally);
81
+ }
82
+ }