dyno-table 2.5.2 → 2.6.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 (76) hide show
  1. package/dist/builders/batch-builder.d.ts +249 -0
  2. package/dist/builders/builder-types.d.ts +123 -0
  3. package/dist/builders/condition-check-builder.d.ts +149 -0
  4. package/dist/builders/delete-builder.d.ts +208 -0
  5. package/dist/builders/entity-aware-builders.d.ts +127 -0
  6. package/dist/builders/filter-builder.d.ts +294 -0
  7. package/dist/builders/get-builder.d.ts +191 -0
  8. package/dist/builders/index.d.ts +14 -0
  9. package/dist/builders/paginator.d.ts +151 -0
  10. package/dist/builders/put-builder.d.ts +317 -0
  11. package/dist/builders/query-builder.d.ts +218 -0
  12. package/dist/builders/result-iterator.d.ts +55 -0
  13. package/dist/builders/scan-builder.d.ts +109 -0
  14. package/dist/builders/transaction-builder.d.ts +462 -0
  15. package/dist/builders/types.d.ts +25 -0
  16. package/dist/builders/update-builder.d.ts +372 -0
  17. package/dist/builders.cjs +3648 -43
  18. package/dist/builders.d.ts +1 -4
  19. package/dist/builders.js +3648 -3
  20. package/dist/conditions.cjs +60 -67
  21. package/dist/conditions.d.ts +705 -3
  22. package/dist/conditions.js +46 -1
  23. package/dist/entity/ddb-indexing.d.ts +45 -0
  24. package/dist/entity/entity.d.ts +188 -0
  25. package/dist/entity/index-utils.d.ts +24 -0
  26. package/dist/entity.cjs +1126 -15
  27. package/dist/entity.d.ts +1 -261
  28. package/dist/entity.js +1127 -3
  29. package/dist/errors.d.ts +212 -0
  30. package/dist/expression.d.ts +9 -0
  31. package/dist/index-definition.d.ts +10 -0
  32. package/dist/index.cjs +5388 -270
  33. package/dist/index.d.ts +16 -273
  34. package/dist/index.js +5332 -6
  35. package/dist/operation-types.d.ts +8 -0
  36. package/dist/standard-schema.d.ts +2 -4
  37. package/dist/table.cjs +4311 -7
  38. package/dist/table.d.ts +13 -8
  39. package/dist/table.js +4315 -4
  40. package/dist/types.d.ts +6 -9
  41. package/dist/utils/chunk-array.d.ts +9 -0
  42. package/dist/utils/debug-expression.d.ts +32 -0
  43. package/dist/utils/debug-transaction.d.ts +17 -0
  44. package/dist/utils/error-factory.d.ts +162 -0
  45. package/dist/utils/error-utils.d.ts +170 -0
  46. package/dist/utils/index.d.ts +7 -0
  47. package/dist/utils/partition-key-template.d.ts +30 -0
  48. package/dist/utils/sort-key-template.d.ts +33 -0
  49. package/dist/utils.cjs +28 -10
  50. package/dist/utils.d.ts +1 -66
  51. package/dist/utils.js +29 -1
  52. package/package.json +53 -66
  53. package/dist/builders.d.cts +0 -4
  54. package/dist/chunk-2WIBY7PZ.js +0 -46
  55. package/dist/chunk-3DR6VOFW.cjs +0 -3349
  56. package/dist/chunk-42LH2UEM.js +0 -577
  57. package/dist/chunk-7UJJ7JXM.cjs +0 -63
  58. package/dist/chunk-ELULXDSB.cjs +0 -564
  59. package/dist/chunk-FF7FYGDH.js +0 -543
  60. package/dist/chunk-G5ERTQFX.cjs +0 -843
  61. package/dist/chunk-NYJGW3XH.js +0 -3334
  62. package/dist/chunk-PB7BBCZO.cjs +0 -32
  63. package/dist/chunk-QVRMYGC4.js +0 -29
  64. package/dist/chunk-RNX2DAHA.js +0 -818
  65. package/dist/chunk-ZUBCW3LA.cjs +0 -579
  66. package/dist/conditions-BSAcZswY.d.ts +0 -731
  67. package/dist/conditions-C8bM__Pn.d.cts +0 -731
  68. package/dist/conditions.d.cts +0 -3
  69. package/dist/entity.d.cts +0 -261
  70. package/dist/index-Bc-ra0im.d.ts +0 -3042
  71. package/dist/index-CPCmWsEv.d.cts +0 -3042
  72. package/dist/index.d.cts +0 -273
  73. package/dist/standard-schema.d.cts +0 -57
  74. package/dist/table.d.cts +0 -165
  75. package/dist/types.d.cts +0 -29
  76. package/dist/utils.d.cts +0 -66
@@ -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/builders/entity-aware-builders.ts
5
- function createEntityAwareBuilder(builder, entityName) {
6
- return new Proxy(builder, {
7
- get(target, prop, receiver) {
8
- if (prop === "entityName") {
9
- return entityName;
10
- }
11
- if (prop === "withBatch" && typeof target[prop] === "function") {
12
- return (batch, entityType) => {
13
- const typeToUse = entityType ?? entityName;
14
- const fn = target[prop];
15
- return fn.call(target, batch, typeToUse);
16
- };
17
- }
18
- return Reflect.get(target, prop, receiver);
19
- }
20
- });
21
- }
22
- function createEntityAwarePutBuilder(builder, entityName) {
23
- return createEntityAwareBuilder(builder, entityName);
24
- }
25
- function createEntityAwareGetBuilder(builder, entityName) {
26
- return createEntityAwareBuilder(builder, entityName);
27
- }
28
- function createEntityAwareDeleteBuilder(builder, entityName) {
29
- return createEntityAwareBuilder(builder, entityName);
30
- }
31
- var EntityAwareUpdateBuilder = class {
32
- forceRebuildIndexes = [];
33
- entityName;
34
- builder;
35
- entityConfig;
36
- updateDataApplied = false;
37
- constructor(builder, entityName) {
38
- this.builder = builder;
39
- this.entityName = entityName;
40
- }
41
- /**
42
- * Configure entity-specific logic for automatic timestamp generation and index updates
43
- */
44
- configureEntityLogic(config) {
45
- this.entityConfig = config;
46
- }
47
- /**
48
- * Forces a rebuild of one or more readonly indexes during the update operation.
49
- *
50
- * By default, readonly indexes are not updated during entity updates to prevent
51
- * errors when required index attributes are missing. This method allows you to
52
- * override that behavior and force specific indexes to be rebuilt.
53
- *
54
- * @example
55
- * ```typescript
56
- * // Force rebuild a single readonly index
57
- * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
58
- * .forceIndexRebuild('gsi1')
59
- * .execute();
60
- *
61
- * // Force rebuild multiple readonly indexes
62
- * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
63
- * .forceIndexRebuild(['gsi1', 'gsi2'])
64
- * .execute();
65
- *
66
- * // Chain with other update operations
67
- * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
68
- * .set('lastUpdated', new Date().toISOString())
69
- * .forceIndexRebuild('gsi1')
70
- * .condition(op => op.eq('status', 'INACTIVE'))
71
- * .execute();
72
- * ```
73
- *
74
- * @param indexes - A single index name or array of index names to force rebuild
75
- * @returns The builder instance for method chaining
76
- */
77
- forceIndexRebuild(indexes) {
78
- if (Array.isArray(indexes)) {
79
- this.forceRebuildIndexes = [...this.forceRebuildIndexes, ...indexes];
80
- } else {
81
- this.forceRebuildIndexes.push(indexes);
82
- }
83
- return this;
84
- }
85
- /**
86
- * Gets the list of indexes that should be force rebuilt.
87
- * This is used internally by entity update logic.
88
- *
89
- * @returns Array of index names to force rebuild
90
- */
91
- getForceRebuildIndexes() {
92
- return [...this.forceRebuildIndexes];
93
- }
94
- /**
95
- * Apply entity-specific update data (timestamps and index updates)
96
- * This is called automatically when needed
97
- */
98
- applyEntityUpdates() {
99
- if (!this.entityConfig || this.updateDataApplied) return;
100
- const timestamps = this.entityConfig.generateTimestamps();
101
- const updatedItem = { ...this.entityConfig.key, ...this.entityConfig.data, ...timestamps };
102
- const indexUpdates = this.entityConfig.buildIndexUpdates(
103
- this.entityConfig.key,
104
- updatedItem,
105
- this.entityConfig.table,
106
- this.entityConfig.indexes,
107
- this.forceRebuildIndexes
108
- );
109
- this.builder.set({ ...this.entityConfig.data, ...timestamps, ...indexUpdates });
110
- this.updateDataApplied = true;
111
- }
112
- set(valuesOrPath, value) {
113
- if (typeof valuesOrPath === "object") {
114
- this.builder.set(valuesOrPath);
115
- } else {
116
- this.builder.set(valuesOrPath, value);
117
- }
118
- return this;
119
- }
120
- remove(path) {
121
- this.builder.remove(path);
122
- return this;
123
- }
124
- add(path, value) {
125
- this.builder.add(path, value);
126
- return this;
127
- }
128
- deleteElementsFromSet(path, value) {
129
- this.builder.deleteElementsFromSet(path, value);
130
- return this;
131
- }
132
- condition(condition) {
133
- this.builder.condition(condition);
134
- return this;
135
- }
136
- returnValues(returnValues) {
137
- this.builder.returnValues(returnValues);
138
- return this;
139
- }
140
- toDynamoCommand() {
141
- return this.builder.toDynamoCommand();
142
- }
143
- withTransaction(transaction) {
144
- this.applyEntityUpdates();
145
- this.builder.withTransaction(transaction);
146
- }
147
- debug() {
148
- return this.builder.debug();
149
- }
150
- async execute() {
151
- this.updateDataApplied = false;
152
- this.applyEntityUpdates();
153
- return this.builder.execute();
154
- }
155
- };
156
- function createEntityAwareUpdateBuilder(builder, entityName) {
157
- return new EntityAwareUpdateBuilder(builder, entityName);
158
- }
159
-
160
- // src/utils/error-utils.ts
161
- function isConditionalCheckFailed(error) {
162
- if (typeof error === "object" && error !== null && "name" in error) {
163
- return error.name === "ConditionalCheckFailedException";
164
- }
165
- return false;
166
- }
167
- function isTransactionCanceled(error) {
168
- if (typeof error === "object" && error !== null && "name" in error) {
169
- return error.name === "TransactionCanceledException";
170
- }
171
- return false;
172
- }
173
- function isValidationException(error) {
174
- if (typeof error === "object" && error !== null && "name" in error) {
175
- return error.name === "ValidationException";
176
- }
177
- return false;
178
- }
179
- function isProvisionedThroughputExceeded(error) {
180
- if (typeof error === "object" && error !== null && "name" in error) {
181
- return error.name === "ProvisionedThroughputExceededException";
182
- }
183
- return false;
184
- }
185
- function isRetryableError(error) {
186
- if (typeof error === "object" && error !== null && "name" in error) {
187
- const errorName = error.name;
188
- return errorName === "ProvisionedThroughputExceededException" || errorName === "ThrottlingException" || errorName === "RequestLimitExceeded" || errorName === "InternalServerError" || errorName === "ServiceUnavailable";
189
- }
190
- return false;
191
- }
192
- function getAwsErrorCode(error) {
193
- if (typeof error === "object" && error !== null && "name" in error) {
194
- return error.name;
195
- }
196
- return void 0;
197
- }
198
- function getAwsErrorMessage(error) {
199
- if (error instanceof Error) {
200
- return error.message;
201
- }
202
- if (typeof error === "object" && error !== null && "message" in error) {
203
- return String(error.message);
204
- }
205
- return void 0;
206
- }
207
- function extractRequiredAttributes(error) {
208
- const message = getAwsErrorMessage(error);
209
- if (!message) return void 0;
210
- const patterns = [
211
- /(?:missing|required)\s+(?:attribute|field|property)(?:s)?[:\s]+([a-zA-Z0-9_,\s]+)/i,
212
- /(?:attribute|field|property)[:\s]+([a-zA-Z0-9_]+)\s+is\s+(?:missing|required)/i,
213
- /"([a-zA-Z0-9_]+)"\s+is\s+(?:missing|required)/i
214
- ];
215
- for (const pattern of patterns) {
216
- const match = message.match(pattern);
217
- if (match?.[1]) {
218
- return match[1].split(",").map((attr) => attr.trim()).filter((attr) => attr.length > 0);
219
- }
220
- }
221
- return void 0;
222
- }
223
- function formatErrorContext(context, indent = 0) {
224
- const indentStr = " ".repeat(indent);
225
- const lines = [];
226
- for (const [key, value] of Object.entries(context)) {
227
- if (value === void 0 || value === null) {
228
- lines.push(`${indentStr}${key}: ${value}`);
229
- } else if (Array.isArray(value)) {
230
- lines.push(`${indentStr}${key}: [${value.map((v) => JSON.stringify(v)).join(", ")}]`);
231
- } else if (typeof value === "object") {
232
- lines.push(`${indentStr}${key}:`);
233
- lines.push(formatErrorContext(value, indent + 1));
234
- } else if (typeof value === "string" && value.length > 100) {
235
- lines.push(`${indentStr}${key}: ${value.substring(0, 100)}...`);
236
- } else {
237
- lines.push(`${indentStr}${key}: ${JSON.stringify(value)}`);
238
- }
239
- }
240
- return lines.join("\n");
241
- }
242
- function getErrorSummary(error) {
243
- const parts = [];
244
- parts.push(`Error: ${error.name}`);
245
- parts.push(`Code: ${error.code}`);
246
- parts.push(`Message: ${error.message}`);
247
- if (Object.keys(error.context).length > 0) {
248
- parts.push("Context:");
249
- parts.push(formatErrorContext(error.context, 1));
250
- }
251
- if (error.cause) {
252
- parts.push(`Caused by: ${error.cause.name}: ${error.cause.message}`);
253
- }
254
- return parts.join("\n");
255
- }
256
- function isDynoTableError(error) {
257
- return typeof error === "object" && error !== null && "code" in error && "context" in error && error instanceof Error;
258
- }
259
- function isValidationError(error) {
260
- return error instanceof Error && error.name === "ValidationError";
261
- }
262
- function isOperationError(error) {
263
- return error instanceof Error && error.name === "OperationError";
264
- }
265
- function isTransactionError(error) {
266
- return error instanceof Error && error.name === "TransactionError";
267
- }
268
- function isBatchError(error) {
269
- return error instanceof Error && error.name === "BatchError";
270
- }
271
- function isExpressionError(error) {
272
- return error instanceof Error && error.name === "ExpressionError";
273
- }
274
- function isConfigurationError(error) {
275
- return error instanceof Error && error.name === "ConfigurationError";
276
- }
277
- function isEntityError(error) {
278
- return error instanceof Error && error.name === "EntityError";
279
- }
280
- function isKeyGenerationError(error) {
281
- return error instanceof Error && error.name === "KeyGenerationError";
282
- }
283
- function isIndexGenerationError(error) {
284
- return error instanceof Error && error.name === "IndexGenerationError";
285
- }
286
- function isEntityValidationError(error) {
287
- return error instanceof Error && error.name === "EntityValidationError";
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 };