dyno-table 2.6.0 → 2.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,818 +0,0 @@
1
- import { EntityErrors, OperationErrors, DynoTableError, ValidationErrors, IndexErrors, ConfigurationErrors } from './chunk-FF7FYGDH.js';
2
- import { eq } from './chunk-2WIBY7PZ.js';
3
-
4
- // src/utils/error-utils.ts
5
- function isConditionalCheckFailed(error) {
6
- if (typeof error === "object" && error !== null && "name" in error) {
7
- return error.name === "ConditionalCheckFailedException";
8
- }
9
- return false;
10
- }
11
- function isTransactionCanceled(error) {
12
- if (typeof error === "object" && error !== null && "name" in error) {
13
- return error.name === "TransactionCanceledException";
14
- }
15
- return false;
16
- }
17
- function isValidationException(error) {
18
- if (typeof error === "object" && error !== null && "name" in error) {
19
- return error.name === "ValidationException";
20
- }
21
- return false;
22
- }
23
- function isProvisionedThroughputExceeded(error) {
24
- if (typeof error === "object" && error !== null && "name" in error) {
25
- return error.name === "ProvisionedThroughputExceededException";
26
- }
27
- return false;
28
- }
29
- function isRetryableError(error) {
30
- if (typeof error === "object" && error !== null && "name" in error) {
31
- const errorName = error.name;
32
- return errorName === "ProvisionedThroughputExceededException" || errorName === "ThrottlingException" || errorName === "RequestLimitExceeded" || errorName === "InternalServerError" || errorName === "ServiceUnavailable";
33
- }
34
- return false;
35
- }
36
- function getAwsErrorCode(error) {
37
- if (typeof error === "object" && error !== null && "name" in error) {
38
- return error.name;
39
- }
40
- return void 0;
41
- }
42
- function getAwsErrorMessage(error) {
43
- if (error instanceof Error) {
44
- return error.message;
45
- }
46
- if (typeof error === "object" && error !== null && "message" in error) {
47
- return String(error.message);
48
- }
49
- return void 0;
50
- }
51
- function extractRequiredAttributes(error) {
52
- const message = getAwsErrorMessage(error);
53
- if (!message) return void 0;
54
- const patterns = [
55
- /(?:missing|required)\s+(?:attribute|field|property)(?:s)?[:\s]+([a-zA-Z0-9_,\s]+)/i,
56
- /(?:attribute|field|property)[:\s]+([a-zA-Z0-9_]+)\s+is\s+(?:missing|required)/i,
57
- /"([a-zA-Z0-9_]+)"\s+is\s+(?:missing|required)/i
58
- ];
59
- for (const pattern of patterns) {
60
- const match = message.match(pattern);
61
- if (match?.[1]) {
62
- return match[1].split(",").map((attr) => attr.trim()).filter((attr) => attr.length > 0);
63
- }
64
- }
65
- return void 0;
66
- }
67
- function formatErrorContext(context, indent = 0) {
68
- const indentStr = " ".repeat(indent);
69
- const lines = [];
70
- for (const [key, value] of Object.entries(context)) {
71
- if (value === void 0 || value === null) {
72
- lines.push(`${indentStr}${key}: ${value}`);
73
- } else if (Array.isArray(value)) {
74
- lines.push(`${indentStr}${key}: [${value.map((v) => JSON.stringify(v)).join(", ")}]`);
75
- } else if (typeof value === "object") {
76
- lines.push(`${indentStr}${key}:`);
77
- lines.push(formatErrorContext(value, indent + 1));
78
- } else if (typeof value === "string" && value.length > 100) {
79
- lines.push(`${indentStr}${key}: ${value.substring(0, 100)}...`);
80
- } else {
81
- lines.push(`${indentStr}${key}: ${JSON.stringify(value)}`);
82
- }
83
- }
84
- return lines.join("\n");
85
- }
86
- function getErrorSummary(error) {
87
- const parts = [];
88
- parts.push(`Error: ${error.name}`);
89
- parts.push(`Code: ${error.code}`);
90
- parts.push(`Message: ${error.message}`);
91
- if (Object.keys(error.context).length > 0) {
92
- parts.push("Context:");
93
- parts.push(formatErrorContext(error.context, 1));
94
- }
95
- if (error.cause) {
96
- parts.push(`Caused by: ${error.cause.name}: ${error.cause.message}`);
97
- }
98
- return parts.join("\n");
99
- }
100
- function isDynoTableError(error) {
101
- return typeof error === "object" && error !== null && "code" in error && "context" in error && error instanceof Error;
102
- }
103
- function isValidationError(error) {
104
- return error instanceof Error && error.name === "ValidationError";
105
- }
106
- function isOperationError(error) {
107
- return error instanceof Error && error.name === "OperationError";
108
- }
109
- function isTransactionError(error) {
110
- return error instanceof Error && error.name === "TransactionError";
111
- }
112
- function isBatchError(error) {
113
- return error instanceof Error && error.name === "BatchError";
114
- }
115
- function isExpressionError(error) {
116
- return error instanceof Error && error.name === "ExpressionError";
117
- }
118
- function isConfigurationError(error) {
119
- return error instanceof Error && error.name === "ConfigurationError";
120
- }
121
- function isEntityError(error) {
122
- return error instanceof Error && error.name === "EntityError";
123
- }
124
- function isKeyGenerationError(error) {
125
- return error instanceof Error && error.name === "KeyGenerationError";
126
- }
127
- function isIndexGenerationError(error) {
128
- return error instanceof Error && error.name === "IndexGenerationError";
129
- }
130
- function isEntityValidationError(error) {
131
- return error instanceof Error && error.name === "EntityValidationError";
132
- }
133
-
134
- // src/builders/entity-aware-builders.ts
135
- function createEntityAwareBuilder(builder, entityName) {
136
- return new Proxy(builder, {
137
- get(target, prop, receiver) {
138
- if (prop === "entityName") {
139
- return entityName;
140
- }
141
- if (prop === "withBatch" && typeof target[prop] === "function") {
142
- return (batch, entityType) => {
143
- const typeToUse = entityType ?? entityName;
144
- const fn = target[prop];
145
- return fn.call(target, batch, typeToUse);
146
- };
147
- }
148
- return Reflect.get(target, prop, receiver);
149
- }
150
- });
151
- }
152
- function createEntityAwarePutBuilder(builder, entityName) {
153
- return createEntityAwareBuilder(builder, entityName);
154
- }
155
- function createEntityAwareGetBuilder(builder, entityName) {
156
- return createEntityAwareBuilder(builder, entityName);
157
- }
158
- function createEntityAwareDeleteBuilder(builder, entityName) {
159
- return createEntityAwareBuilder(builder, entityName);
160
- }
161
- var EntityAwareUpdateBuilder = class {
162
- forceRebuildIndexes = [];
163
- entityName;
164
- builder;
165
- entityConfig;
166
- updateDataApplied = false;
167
- constructor(builder, entityName) {
168
- this.builder = builder;
169
- this.entityName = entityName;
170
- }
171
- /**
172
- * Configure entity-specific logic for automatic timestamp generation and index updates
173
- */
174
- configureEntityLogic(config) {
175
- this.entityConfig = config;
176
- }
177
- /**
178
- * Forces a rebuild of one or more readonly indexes during the update operation.
179
- *
180
- * By default, readonly indexes are not updated during entity updates to prevent
181
- * errors when required index attributes are missing. This method allows you to
182
- * override that behavior and force specific indexes to be rebuilt.
183
- *
184
- * @example
185
- * ```typescript
186
- * // Force rebuild a single readonly index
187
- * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
188
- * .forceIndexRebuild('gsi1')
189
- * .execute();
190
- *
191
- * // Force rebuild multiple readonly indexes
192
- * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
193
- * .forceIndexRebuild(['gsi1', 'gsi2'])
194
- * .execute();
195
- *
196
- * // Chain with other update operations
197
- * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
198
- * .set('lastUpdated', new Date().toISOString())
199
- * .forceIndexRebuild('gsi1')
200
- * .condition(op => op.eq('status', 'INACTIVE'))
201
- * .execute();
202
- * ```
203
- *
204
- * @param indexes - A single index name or array of index names to force rebuild
205
- * @returns The builder instance for method chaining
206
- */
207
- forceIndexRebuild(indexes) {
208
- if (Array.isArray(indexes)) {
209
- this.forceRebuildIndexes = [...this.forceRebuildIndexes, ...indexes];
210
- } else {
211
- this.forceRebuildIndexes.push(indexes);
212
- }
213
- return this;
214
- }
215
- /**
216
- * Gets the list of indexes that should be force rebuilt.
217
- * This is used internally by entity update logic.
218
- *
219
- * @returns Array of index names to force rebuild
220
- */
221
- getForceRebuildIndexes() {
222
- return [...this.forceRebuildIndexes];
223
- }
224
- /**
225
- * Apply entity-specific update data (timestamps and index updates)
226
- * This is called automatically when needed
227
- */
228
- applyEntityUpdates() {
229
- if (!this.entityConfig || this.updateDataApplied) return;
230
- const timestamps = this.entityConfig.generateTimestamps();
231
- const updatedItem = { ...this.entityConfig.key, ...this.entityConfig.data, ...timestamps };
232
- const indexUpdates = this.entityConfig.buildIndexUpdates(
233
- this.entityConfig.key,
234
- updatedItem,
235
- this.entityConfig.table,
236
- this.entityConfig.indexes,
237
- this.forceRebuildIndexes
238
- );
239
- this.builder.set({ ...this.entityConfig.data, ...timestamps, ...indexUpdates });
240
- this.updateDataApplied = true;
241
- }
242
- set(valuesOrPath, value) {
243
- if (typeof valuesOrPath === "object") {
244
- this.builder.set(valuesOrPath);
245
- } else {
246
- this.builder.set(valuesOrPath, value);
247
- }
248
- return this;
249
- }
250
- remove(path) {
251
- this.builder.remove(path);
252
- return this;
253
- }
254
- add(path, value) {
255
- this.builder.add(path, value);
256
- return this;
257
- }
258
- deleteElementsFromSet(path, value) {
259
- this.builder.deleteElementsFromSet(path, value);
260
- return this;
261
- }
262
- condition(condition) {
263
- this.builder.condition(condition);
264
- return this;
265
- }
266
- returnValues(returnValues) {
267
- this.builder.returnValues(returnValues);
268
- return this;
269
- }
270
- toDynamoCommand() {
271
- return this.builder.toDynamoCommand();
272
- }
273
- withTransaction(transaction) {
274
- this.applyEntityUpdates();
275
- this.builder.withTransaction(transaction);
276
- }
277
- debug() {
278
- return this.builder.debug();
279
- }
280
- async execute() {
281
- this.updateDataApplied = false;
282
- this.applyEntityUpdates();
283
- return this.builder.execute();
284
- }
285
- };
286
- function createEntityAwareUpdateBuilder(builder, entityName) {
287
- return new EntityAwareUpdateBuilder(builder, entityName);
288
- }
289
-
290
- // src/entity/ddb-indexing.ts
291
- var IndexBuilder = class {
292
- /**
293
- * Creates a new IndexBuilder instance
294
- *
295
- * @param table - The DynamoDB table instance
296
- * @param indexes - The index definitions
297
- */
298
- constructor(table, indexes = {}) {
299
- this.table = table;
300
- this.indexes = indexes;
301
- }
302
- /**
303
- * Build index attributes for item creation
304
- *
305
- * @param item - The item to generate indexes for
306
- * @param options - Options for building indexes
307
- * @returns Record of GSI attribute names to their values
308
- */
309
- buildForCreate(item, options = {}) {
310
- const attributes = {};
311
- for (const [indexName, indexDef] of Object.entries(this.indexes)) {
312
- if (options.excludeReadOnly && indexDef.isReadOnly) {
313
- continue;
314
- }
315
- let key;
316
- try {
317
- key = indexDef.generateKey(item);
318
- if (this.hasUndefinedValues(key)) {
319
- throw IndexErrors.undefinedValues(indexName, "create", key, item);
320
- }
321
- } catch (error) {
322
- if (error instanceof DynoTableError) throw error;
323
- throw IndexErrors.generationFailed(
324
- indexName,
325
- "create",
326
- item,
327
- indexDef.partitionKey,
328
- indexDef.sortKey,
329
- error instanceof Error ? error : void 0
330
- );
331
- }
332
- const gsiConfig = this.table.gsis[indexName];
333
- if (!gsiConfig) {
334
- throw ConfigurationErrors.gsiNotFound(indexName, this.table.tableName, Object.keys(this.table.gsis));
335
- }
336
- if (key.pk) {
337
- attributes[gsiConfig.partitionKey] = key.pk;
338
- }
339
- if (key.sk && gsiConfig.sortKey) {
340
- attributes[gsiConfig.sortKey] = key.sk;
341
- }
342
- }
343
- return attributes;
344
- }
345
- /**
346
- * Build index attributes for item updates
347
- *
348
- * @param currentData - The current data before update
349
- * @param updates - The update data
350
- * @param options - Options for building indexes
351
- * @returns Record of GSI attribute names to their updated values
352
- */
353
- buildForUpdate(currentData, updates, options = {}) {
354
- const attributes = {};
355
- const updatedItem = { ...currentData, ...updates };
356
- if (options.forceRebuildIndexes && options.forceRebuildIndexes.length > 0) {
357
- const invalidIndexes = options.forceRebuildIndexes.filter((indexName) => !this.indexes[indexName]);
358
- if (invalidIndexes.length > 0) {
359
- throw IndexErrors.notFound(invalidIndexes, Object.keys(this.indexes), void 0, this.table.tableName);
360
- }
361
- }
362
- for (const [indexName, indexDef] of Object.entries(this.indexes)) {
363
- const isForced = options.forceRebuildIndexes?.includes(indexName);
364
- if (indexDef.isReadOnly && !isForced) {
365
- continue;
366
- }
367
- if (!isForced) {
368
- let shouldUpdateIndex = false;
369
- try {
370
- const currentKey = indexDef.generateKey(currentData);
371
- const updatedKey = indexDef.generateKey(updatedItem);
372
- if (currentKey.pk !== updatedKey.pk || currentKey.sk !== updatedKey.sk) {
373
- shouldUpdateIndex = true;
374
- }
375
- } catch {
376
- shouldUpdateIndex = true;
377
- }
378
- if (!shouldUpdateIndex) {
379
- continue;
380
- }
381
- }
382
- let key;
383
- try {
384
- key = indexDef.generateKey(updatedItem);
385
- } catch (error) {
386
- if (error instanceof DynoTableError) throw error;
387
- throw IndexErrors.missingAttributes(
388
- indexName,
389
- "update",
390
- [],
391
- // We don't know which specific attributes are missing from the error
392
- updates,
393
- indexDef.isReadOnly
394
- );
395
- }
396
- if (this.hasUndefinedValues(key)) {
397
- throw IndexErrors.undefinedValues(indexName, "update", key, updates);
398
- }
399
- const gsiConfig = this.table.gsis[indexName];
400
- if (!gsiConfig) {
401
- throw ConfigurationErrors.gsiNotFound(indexName, this.table.tableName, Object.keys(this.table.gsis));
402
- }
403
- if (key.pk) {
404
- attributes[gsiConfig.partitionKey] = key.pk;
405
- }
406
- if (key.sk && gsiConfig.sortKey) {
407
- attributes[gsiConfig.sortKey] = key.sk;
408
- }
409
- }
410
- return attributes;
411
- }
412
- /**
413
- * Check if a key has undefined values
414
- *
415
- * @param key - The index key to check
416
- * @returns True if the key contains undefined values, false otherwise
417
- */
418
- hasUndefinedValues(key) {
419
- return (key.pk?.includes("undefined") ?? false) || (key.sk?.includes("undefined") ?? false);
420
- }
421
- };
422
-
423
- // src/entity/index-utils.ts
424
- function buildIndexes(dataForKeyGeneration, table, indexes, excludeReadOnly = false) {
425
- if (!indexes) {
426
- return {};
427
- }
428
- const indexBuilder = new IndexBuilder(table, indexes);
429
- return indexBuilder.buildForCreate(dataForKeyGeneration, { excludeReadOnly });
430
- }
431
- function buildIndexUpdates(currentData, updates, table, indexes, forceRebuildIndexes) {
432
- if (!indexes) {
433
- return {};
434
- }
435
- const indexBuilder = new IndexBuilder(table, indexes);
436
- return indexBuilder.buildForUpdate(currentData, updates, { forceRebuildIndexes });
437
- }
438
-
439
- // src/entity/entity.ts
440
- function defineEntity(config) {
441
- const entityTypeAttributeName = config.settings?.entityTypeAttributeName ?? "entityType";
442
- const buildIndexes2 = (dataForKeyGeneration, table, excludeReadOnly = false) => {
443
- return buildIndexes(dataForKeyGeneration, table, config.indexes, excludeReadOnly);
444
- };
445
- const wrapMethodWithPreparation = (originalMethod, prepareFn, context) => {
446
- const wrappedMethod = (...args) => {
447
- prepareFn();
448
- return originalMethod.call(context, ...args);
449
- };
450
- Object.setPrototypeOf(wrappedMethod, originalMethod);
451
- const propertyNames = Object.getOwnPropertyNames(originalMethod);
452
- for (let i = 0; i < propertyNames.length; i++) {
453
- const prop = propertyNames[i];
454
- if (prop !== "length" && prop !== "name" && prop !== "prototype") {
455
- const descriptor = Object.getOwnPropertyDescriptor(originalMethod, prop);
456
- if (descriptor && descriptor.writable !== false && !descriptor.get) {
457
- wrappedMethod[prop] = originalMethod[prop];
458
- }
459
- }
460
- }
461
- return wrappedMethod;
462
- };
463
- const generateTimestamps = (timestampsToGenerate, data) => {
464
- if (!config.settings?.timestamps) return {};
465
- const timestamps = {};
466
- const now = /* @__PURE__ */ new Date();
467
- const unixTime = Math.floor(Date.now() / 1e3);
468
- const { createdAt, updatedAt } = config.settings.timestamps;
469
- if (createdAt && timestampsToGenerate.includes("createdAt") && !data.createdAt) {
470
- const name = createdAt.attributeName ?? "createdAt";
471
- timestamps[name] = createdAt.format === "UNIX" ? unixTime : now.toISOString();
472
- }
473
- if (updatedAt && timestampsToGenerate.includes("updatedAt") && !data.updatedAt) {
474
- const name = updatedAt.attributeName ?? "updatedAt";
475
- timestamps[name] = updatedAt.format === "UNIX" ? unixTime : now.toISOString();
476
- }
477
- return timestamps;
478
- };
479
- return {
480
- name: config.name,
481
- createRepository: (table) => {
482
- const repository = {
483
- create: (data) => {
484
- const builder = table.create({});
485
- const prepareValidatedItemAsync = async () => {
486
- const validatedData = await config.schema["~standard"].validate(data);
487
- if ("issues" in validatedData && validatedData.issues) {
488
- throw EntityErrors.validationFailed(config.name, "create", validatedData.issues, data);
489
- }
490
- const dataForKeyGeneration = {
491
- ...validatedData.value,
492
- ...generateTimestamps(["createdAt", "updatedAt"], validatedData.value)
493
- };
494
- let primaryKey;
495
- try {
496
- primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
497
- if (primaryKey.pk === void 0 || primaryKey.pk === null) {
498
- throw EntityErrors.keyInvalidFormat(config.name, "create", dataForKeyGeneration, primaryKey);
499
- }
500
- } catch (error) {
501
- if (error instanceof DynoTableError) throw error;
502
- throw EntityErrors.keyGenerationFailed(
503
- config.name,
504
- "create",
505
- dataForKeyGeneration,
506
- extractRequiredAttributes(error),
507
- error instanceof Error ? error : void 0
508
- );
509
- }
510
- const indexes = buildIndexes(dataForKeyGeneration, table, config.indexes, false);
511
- const validatedItem = {
512
- ...dataForKeyGeneration,
513
- [entityTypeAttributeName]: config.name,
514
- [table.partitionKey]: primaryKey.pk,
515
- ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
516
- ...indexes
517
- };
518
- Object.assign(builder, { item: validatedItem });
519
- return validatedItem;
520
- };
521
- const prepareValidatedItemSync = () => {
522
- const validationResult = config.schema["~standard"].validate(data);
523
- if (validationResult instanceof Promise) {
524
- throw EntityErrors.asyncValidationNotSupported(config.name, "create");
525
- }
526
- if ("issues" in validationResult && validationResult.issues) {
527
- throw EntityErrors.validationFailed(config.name, "create", validationResult.issues, data);
528
- }
529
- const dataForKeyGeneration = {
530
- ...validationResult.value,
531
- ...generateTimestamps(["createdAt", "updatedAt"], validationResult.value)
532
- };
533
- let primaryKey;
534
- try {
535
- primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
536
- if (primaryKey.pk === void 0 || primaryKey.pk === null) {
537
- throw EntityErrors.keyInvalidFormat(config.name, "create", dataForKeyGeneration, primaryKey);
538
- }
539
- } catch (error) {
540
- if (error instanceof DynoTableError) throw error;
541
- throw EntityErrors.keyGenerationFailed(
542
- config.name,
543
- "create",
544
- dataForKeyGeneration,
545
- extractRequiredAttributes(error),
546
- error instanceof Error ? error : void 0
547
- );
548
- }
549
- const indexes = buildIndexes(dataForKeyGeneration, table, config.indexes, false);
550
- const validatedItem = {
551
- ...dataForKeyGeneration,
552
- [entityTypeAttributeName]: config.name,
553
- [table.partitionKey]: primaryKey.pk,
554
- ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
555
- ...indexes
556
- };
557
- Object.assign(builder, { item: validatedItem });
558
- return validatedItem;
559
- };
560
- const originalExecute = builder.execute;
561
- builder.execute = async () => {
562
- await prepareValidatedItemAsync();
563
- return await originalExecute.call(builder);
564
- };
565
- const originalWithTransaction = builder.withTransaction;
566
- if (originalWithTransaction) {
567
- builder.withTransaction = wrapMethodWithPreparation(
568
- originalWithTransaction,
569
- prepareValidatedItemSync,
570
- builder
571
- );
572
- }
573
- const originalWithBatch = builder.withBatch;
574
- if (originalWithBatch) {
575
- builder.withBatch = wrapMethodWithPreparation(originalWithBatch, prepareValidatedItemSync, builder);
576
- }
577
- return createEntityAwarePutBuilder(builder, config.name);
578
- },
579
- upsert: (data) => {
580
- const builder = table.put({});
581
- const prepareValidatedItemAsync = async () => {
582
- const validatedData = await config.schema["~standard"].validate(data);
583
- if ("issues" in validatedData && validatedData.issues) {
584
- throw EntityErrors.validationFailed(config.name, "upsert", validatedData.issues, data);
585
- }
586
- const dataForKeyGeneration = {
587
- ...validatedData.value,
588
- ...generateTimestamps(["createdAt", "updatedAt"], validatedData.value)
589
- };
590
- let primaryKey;
591
- try {
592
- primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
593
- if (primaryKey.pk === void 0 || primaryKey.pk === null) {
594
- throw EntityErrors.keyInvalidFormat(config.name, "upsert", dataForKeyGeneration, primaryKey);
595
- }
596
- } catch (error) {
597
- if (error instanceof DynoTableError) throw error;
598
- throw EntityErrors.keyGenerationFailed(
599
- config.name,
600
- "upsert",
601
- dataForKeyGeneration,
602
- extractRequiredAttributes(error),
603
- error instanceof Error ? error : void 0
604
- );
605
- }
606
- const indexes = buildIndexes2(dataForKeyGeneration, table, false);
607
- const validatedItem = {
608
- [table.partitionKey]: primaryKey.pk,
609
- ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
610
- ...dataForKeyGeneration,
611
- [entityTypeAttributeName]: config.name,
612
- ...indexes
613
- };
614
- Object.assign(builder, { item: validatedItem });
615
- return validatedItem;
616
- };
617
- const prepareValidatedItemSync = () => {
618
- const validationResult = config.schema["~standard"].validate(data);
619
- if (validationResult instanceof Promise) {
620
- throw EntityErrors.asyncValidationNotSupported(config.name, "upsert");
621
- }
622
- if ("issues" in validationResult && validationResult.issues) {
623
- throw EntityErrors.validationFailed(config.name, "upsert", validationResult.issues, data);
624
- }
625
- const dataForKeyGeneration = {
626
- ...validationResult.value,
627
- ...generateTimestamps(["createdAt", "updatedAt"], validationResult.value)
628
- };
629
- let primaryKey;
630
- try {
631
- primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
632
- if (primaryKey.pk === void 0 || primaryKey.pk === null) {
633
- throw EntityErrors.keyInvalidFormat(config.name, "upsert", dataForKeyGeneration, primaryKey);
634
- }
635
- } catch (error) {
636
- if (error instanceof DynoTableError) throw error;
637
- throw EntityErrors.keyGenerationFailed(
638
- config.name,
639
- "upsert",
640
- dataForKeyGeneration,
641
- extractRequiredAttributes(error),
642
- error instanceof Error ? error : void 0
643
- );
644
- }
645
- const indexes = buildIndexes(dataForKeyGeneration, table, config.indexes, false);
646
- const validatedItem = {
647
- [table.partitionKey]: primaryKey.pk,
648
- ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
649
- ...dataForKeyGeneration,
650
- [entityTypeAttributeName]: config.name,
651
- ...indexes
652
- };
653
- Object.assign(builder, { item: validatedItem });
654
- return validatedItem;
655
- };
656
- const originalExecute = builder.execute;
657
- builder.execute = async () => {
658
- const validatedItem = await prepareValidatedItemAsync();
659
- await originalExecute.call(builder);
660
- return validatedItem;
661
- };
662
- const originalWithTransaction = builder.withTransaction;
663
- if (originalWithTransaction) {
664
- builder.withTransaction = wrapMethodWithPreparation(
665
- originalWithTransaction,
666
- prepareValidatedItemSync,
667
- builder
668
- );
669
- }
670
- const originalWithBatch = builder.withBatch;
671
- if (originalWithBatch) {
672
- builder.withBatch = wrapMethodWithPreparation(originalWithBatch, prepareValidatedItemSync, builder);
673
- }
674
- return createEntityAwarePutBuilder(builder, config.name);
675
- },
676
- get: (key) => {
677
- const builder = table.get(config.primaryKey.generateKey(key));
678
- return createEntityAwareGetBuilder(builder, config.name);
679
- },
680
- update: (key, data) => {
681
- const primaryKeyObj = config.primaryKey.generateKey(key);
682
- const builder = table.update(primaryKeyObj);
683
- builder.condition(eq(entityTypeAttributeName, config.name));
684
- const entityAwareBuilder = createEntityAwareUpdateBuilder(builder, config.name);
685
- entityAwareBuilder.configureEntityLogic({
686
- data,
687
- key,
688
- table,
689
- indexes: config.indexes,
690
- generateTimestamps: () => generateTimestamps(["updatedAt"], data),
691
- buildIndexUpdates
692
- });
693
- return entityAwareBuilder;
694
- },
695
- delete: (key) => {
696
- const builder = table.delete(config.primaryKey.generateKey(key));
697
- builder.condition(eq(entityTypeAttributeName, config.name));
698
- return createEntityAwareDeleteBuilder(builder, config.name);
699
- },
700
- query: Object.entries(config.queries || {}).reduce(
701
- (acc, [key, inputCallback]) => {
702
- acc[key] = (input) => {
703
- const queryEntity = {
704
- scan: repository.scan,
705
- get: (key2) => createEntityAwareGetBuilder(table.get(key2), config.name),
706
- query: (keyCondition) => {
707
- return table.query(keyCondition);
708
- }
709
- };
710
- const queryBuilderCallback = inputCallback(input);
711
- const builder = queryBuilderCallback(queryEntity);
712
- if (builder && typeof builder === "object" && "filter" in builder && typeof builder.filter === "function") {
713
- builder.filter(eq(entityTypeAttributeName, config.name));
714
- }
715
- if (builder && typeof builder === "object" && "execute" in builder) {
716
- const originalExecute = builder.execute;
717
- builder.execute = async () => {
718
- const queryFn = config.queries[key];
719
- if (queryFn && typeof queryFn === "function") {
720
- const schema = queryFn.schema;
721
- if (schema?.["~standard"]?.validate && typeof schema["~standard"].validate === "function") {
722
- const validationResult = schema["~standard"].validate(input);
723
- if ("issues" in validationResult && validationResult.issues) {
724
- throw EntityErrors.queryInputValidationFailed(config.name, key, validationResult.issues, input);
725
- }
726
- }
727
- }
728
- const result = await originalExecute.call(builder);
729
- if (!result) {
730
- throw OperationErrors.queryFailed(config.name, { queryName: key }, void 0);
731
- }
732
- return result;
733
- };
734
- }
735
- return builder;
736
- };
737
- return acc;
738
- },
739
- {}
740
- ),
741
- scan: () => {
742
- const builder = table.scan();
743
- builder.filter(eq(entityTypeAttributeName, config.name));
744
- return builder;
745
- }
746
- };
747
- return repository;
748
- }
749
- };
750
- }
751
- function createQueries() {
752
- return {
753
- input: (schema) => ({
754
- query: (handler) => {
755
- const queryFn = (input) => (entity) => handler({ input, entity });
756
- queryFn.schema = schema;
757
- return queryFn;
758
- }
759
- })
760
- };
761
- }
762
- function createIndex() {
763
- return {
764
- input: (schema) => {
765
- const createIndexBuilder = (isReadOnly = false) => ({
766
- partitionKey: (pkFn) => ({
767
- sortKey: (skFn) => {
768
- const index = {
769
- name: "custom",
770
- partitionKey: "pk",
771
- sortKey: "sk",
772
- isReadOnly,
773
- generateKey: (item) => {
774
- const data = schema["~standard"].validate(item);
775
- if ("issues" in data && data.issues) {
776
- throw ValidationErrors.indexSchemaValidationFailed(data.issues, "both");
777
- }
778
- const validData = "value" in data ? data.value : item;
779
- return { pk: pkFn(validData), sk: skFn(validData) };
780
- }
781
- };
782
- return Object.assign(index, {
783
- readOnly: (value = false) => ({
784
- ...index,
785
- isReadOnly: value
786
- })
787
- });
788
- },
789
- withoutSortKey: () => {
790
- const index = {
791
- name: "custom",
792
- partitionKey: "pk",
793
- isReadOnly,
794
- generateKey: (item) => {
795
- const data = schema["~standard"].validate(item);
796
- if ("issues" in data && data.issues) {
797
- throw ValidationErrors.indexSchemaValidationFailed(data.issues, "partition");
798
- }
799
- const validData = "value" in data ? data.value : item;
800
- return { pk: pkFn(validData) };
801
- }
802
- };
803
- return Object.assign(index, {
804
- readOnly: (value = true) => ({
805
- ...index,
806
- isReadOnly: value
807
- })
808
- });
809
- }
810
- }),
811
- readOnly: (value = true) => createIndexBuilder(value)
812
- });
813
- return createIndexBuilder(false);
814
- }
815
- };
816
- }
817
-
818
- export { createIndex, createQueries, defineEntity, extractRequiredAttributes, formatErrorContext, getAwsErrorCode, getAwsErrorMessage, getErrorSummary, isBatchError, isConditionalCheckFailed, isConfigurationError, isDynoTableError, isEntityError, isEntityValidationError, isExpressionError, isIndexGenerationError, isKeyGenerationError, isOperationError, isProvisionedThroughputExceeded, isRetryableError, isTransactionCanceled, isTransactionError, isValidationError, isValidationException };