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