dyno-table 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +200 -1860
- package/dist/builders.cjs +55 -0
- package/dist/builders.d.cts +4 -0
- package/dist/builders.d.ts +4 -0
- package/dist/builders.js +2 -0
- package/dist/chunk-2EWNZOUK.js +618 -0
- package/dist/chunk-2WIBY7PZ.js +46 -0
- package/dist/chunk-7UJJ7JXM.cjs +63 -0
- package/dist/chunk-DTFJJASK.js +3200 -0
- package/dist/chunk-EODPMYPE.js +558 -0
- package/dist/chunk-KA3VPIPS.cjs +560 -0
- package/dist/chunk-NTA6GDPP.cjs +622 -0
- package/dist/chunk-PB7BBCZO.cjs +32 -0
- package/dist/chunk-QVRMYGC4.js +29 -0
- package/dist/chunk-XYL43FDX.cjs +3217 -0
- package/dist/conditions.cjs +67 -62
- package/dist/conditions.js +1 -48
- package/dist/entity.cjs +14 -625
- package/dist/entity.d.cts +2 -10
- package/dist/entity.d.ts +2 -10
- package/dist/entity.js +2 -626
- package/dist/index-2cbm07Bi.d.ts +2797 -0
- package/dist/index-DlN8G9hd.d.cts +2797 -0
- package/dist/index.cjs +111 -4460
- package/dist/index.d.cts +2 -10
- package/dist/index.d.ts +2 -10
- package/dist/index.js +5 -4442
- package/dist/standard-schema.cjs +0 -2
- package/dist/standard-schema.js +0 -2
- package/dist/table.cjs +7 -3796
- package/dist/table.d.cts +163 -12
- package/dist/table.d.ts +163 -12
- package/dist/table.js +3 -3799
- package/dist/types.cjs +0 -2
- package/dist/types.js +0 -2
- package/dist/utils.cjs +10 -30
- package/dist/utils.js +1 -31
- package/package.json +6 -66
- package/dist/batch-builder-BiQDIZ7p.d.cts +0 -398
- package/dist/batch-builder-CNsLS6sR.d.ts +0 -398
- package/dist/builder-types-BTVhQSHI.d.cts +0 -169
- package/dist/builder-types-CzuLR4Th.d.ts +0 -169
- package/dist/builders/condition-check-builder.cjs +0 -422
- package/dist/builders/condition-check-builder.cjs.map +0 -1
- package/dist/builders/condition-check-builder.d.cts +0 -153
- package/dist/builders/condition-check-builder.d.ts +0 -153
- package/dist/builders/condition-check-builder.js +0 -420
- package/dist/builders/condition-check-builder.js.map +0 -1
- package/dist/builders/delete-builder.cjs +0 -484
- package/dist/builders/delete-builder.cjs.map +0 -1
- package/dist/builders/delete-builder.d.cts +0 -211
- package/dist/builders/delete-builder.d.ts +0 -211
- package/dist/builders/delete-builder.js +0 -482
- package/dist/builders/delete-builder.js.map +0 -1
- package/dist/builders/paginator.cjs +0 -193
- package/dist/builders/paginator.cjs.map +0 -1
- package/dist/builders/paginator.d.cts +0 -155
- package/dist/builders/paginator.d.ts +0 -155
- package/dist/builders/paginator.js +0 -191
- package/dist/builders/paginator.js.map +0 -1
- package/dist/builders/put-builder.cjs +0 -554
- package/dist/builders/put-builder.cjs.map +0 -1
- package/dist/builders/put-builder.d.cts +0 -319
- package/dist/builders/put-builder.d.ts +0 -319
- package/dist/builders/put-builder.js +0 -552
- package/dist/builders/put-builder.js.map +0 -1
- package/dist/builders/query-builder.cjs +0 -757
- package/dist/builders/query-builder.cjs.map +0 -1
- package/dist/builders/query-builder.d.cts +0 -6
- package/dist/builders/query-builder.d.ts +0 -6
- package/dist/builders/query-builder.js +0 -755
- package/dist/builders/query-builder.js.map +0 -1
- package/dist/builders/transaction-builder.cjs +0 -906
- package/dist/builders/transaction-builder.cjs.map +0 -1
- package/dist/builders/transaction-builder.d.cts +0 -464
- package/dist/builders/transaction-builder.d.ts +0 -464
- package/dist/builders/transaction-builder.js +0 -904
- package/dist/builders/transaction-builder.js.map +0 -1
- package/dist/builders/update-builder.cjs +0 -668
- package/dist/builders/update-builder.cjs.map +0 -1
- package/dist/builders/update-builder.d.cts +0 -374
- package/dist/builders/update-builder.d.ts +0 -374
- package/dist/builders/update-builder.js +0 -666
- package/dist/builders/update-builder.js.map +0 -1
- package/dist/conditions.cjs.map +0 -1
- package/dist/conditions.js.map +0 -1
- package/dist/entity.cjs.map +0 -1
- package/dist/entity.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/query-builder-D3URwK9k.d.cts +0 -477
- package/dist/query-builder-cfEkU0_w.d.ts +0 -477
- package/dist/standard-schema.cjs.map +0 -1
- package/dist/standard-schema.js.map +0 -1
- package/dist/table-ClST8nkR.d.cts +0 -276
- package/dist/table-vE3cGoDy.d.ts +0 -276
- package/dist/table.cjs.map +0 -1
- package/dist/table.js.map +0 -1
- package/dist/types.cjs.map +0 -1
- package/dist/types.js.map +0 -1
- package/dist/utils.cjs.map +0 -1
- package/dist/utils.js.map +0 -1
|
@@ -0,0 +1,2797 @@
|
|
|
1
|
+
import { c as PrimaryKeyWithoutExpression, s as Path, a as Condition, b as ConditionOperator, t as PathType } from './conditions-CcZL0sR2.cjs';
|
|
2
|
+
import { DynamoItem, TableConfig, GSINames } from './types.cjs';
|
|
3
|
+
import { TransactWriteCommandInput } from '@aws-sdk/lib-dynamodb';
|
|
4
|
+
|
|
5
|
+
type BatchWriteOperation<T extends Record<string, unknown>> = {
|
|
6
|
+
type: "put";
|
|
7
|
+
item: T;
|
|
8
|
+
} | {
|
|
9
|
+
type: "delete";
|
|
10
|
+
key: PrimaryKeyWithoutExpression;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Interface for DynamoDB command objects that can contain expressions
|
|
15
|
+
*/
|
|
16
|
+
interface DynamoCommandWithExpressions {
|
|
17
|
+
conditionExpression?: string;
|
|
18
|
+
updateExpression?: string;
|
|
19
|
+
filterExpression?: string;
|
|
20
|
+
keyConditionExpression?: string;
|
|
21
|
+
projectionExpression?: string;
|
|
22
|
+
expressionAttributeNames?: Record<string, string>;
|
|
23
|
+
expressionAttributeValues?: Record<string, unknown>;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Function type for executing DynamoDB operations and returning raw results.
|
|
29
|
+
*/
|
|
30
|
+
type DirectExecutor<T extends DynamoItem> = () => Promise<{
|
|
31
|
+
items: T[];
|
|
32
|
+
lastEvaluatedKey?: DynamoItem;
|
|
33
|
+
}>;
|
|
34
|
+
/**
|
|
35
|
+
* Minimal result generator that provides async iteration over DynamoDB results with automatic pagination.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* const results = await queryBuilder.execute();
|
|
40
|
+
*
|
|
41
|
+
* for await (const item of results) {
|
|
42
|
+
* console.log(item);
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
declare class ResultIterator<T extends DynamoItem, TConfig extends TableConfig = TableConfig> {
|
|
47
|
+
private queryBuilder;
|
|
48
|
+
private directExecutor;
|
|
49
|
+
private lastEvaluatedKey?;
|
|
50
|
+
private itemsYielded;
|
|
51
|
+
private readonly overallLimit?;
|
|
52
|
+
constructor(queryBuilder: QueryBuilderInterface<T, TConfig>, directExecutor: DirectExecutor<T>);
|
|
53
|
+
/**
|
|
54
|
+
* Async iterator with automatic pagination
|
|
55
|
+
*/
|
|
56
|
+
[Symbol.asyncIterator](): AsyncIterableIterator<T>;
|
|
57
|
+
/**
|
|
58
|
+
* Convert to array (loads all pages).
|
|
59
|
+
*
|
|
60
|
+
* ```ts
|
|
61
|
+
* const result = await table.query({ pk: "foo" }).execute();
|
|
62
|
+
* const allItemsFromDynamo = await result.toArray();
|
|
63
|
+
* ```
|
|
64
|
+
*
|
|
65
|
+
* Note: This will load all pages into memory. For large datasets, consider using async iteration instead.
|
|
66
|
+
*```ts
|
|
67
|
+
* const result = await table.query({ pk: "foo" }).execute();
|
|
68
|
+
* for await (const item of result) {
|
|
69
|
+
* // Process each item
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
toArray(): Promise<T[]>;
|
|
74
|
+
/**
|
|
75
|
+
* Get the last evaluated key
|
|
76
|
+
*/
|
|
77
|
+
getLastEvaluatedKey(): DynamoItem | undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface DeleteCommandParams extends DynamoCommandWithExpressions {
|
|
81
|
+
tableName: string;
|
|
82
|
+
key: Record<string, unknown>;
|
|
83
|
+
conditionExpression?: string;
|
|
84
|
+
expressionAttributeNames?: Record<string, string>;
|
|
85
|
+
expressionAttributeValues?: DynamoItem;
|
|
86
|
+
returnValues?: "ALL_OLD";
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Parameters for the DynamoDB put command.
|
|
90
|
+
*
|
|
91
|
+
* These parameters are used when executing the operation against DynamoDB.
|
|
92
|
+
*
|
|
93
|
+
* The `returnValues` property can be:
|
|
94
|
+
* - `"ALL_OLD"`: Return the attributes of the item as they were before the operation
|
|
95
|
+
* - `"NONE"`: Return nothing
|
|
96
|
+
* - `"CONSISTENT"`: Triggers a GET operation after the put to retrieve the updated item state
|
|
97
|
+
* - `"INPUT"`: Return the input values that were passed to the operation (useful for create operations)
|
|
98
|
+
*/
|
|
99
|
+
interface PutCommandParams extends DynamoCommandWithExpressions {
|
|
100
|
+
tableName: string;
|
|
101
|
+
item: DynamoItem;
|
|
102
|
+
conditionExpression?: string;
|
|
103
|
+
expressionAttributeNames?: Record<string, string>;
|
|
104
|
+
expressionAttributeValues?: Record<string, unknown>;
|
|
105
|
+
returnValues?: "ALL_OLD" | "NONE" | "CONSISTENT" | "INPUT";
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Parameters for the DynamoDB update command.
|
|
109
|
+
* These parameters are used when executing the operation against DynamoDB.
|
|
110
|
+
*/
|
|
111
|
+
interface UpdateCommandParams extends DynamoCommandWithExpressions {
|
|
112
|
+
/** The name of the DynamoDB table */
|
|
113
|
+
tableName: string;
|
|
114
|
+
/** The primary key of the item to update */
|
|
115
|
+
key: Record<string, unknown>;
|
|
116
|
+
/** The update expression (SET, REMOVE, ADD, DELETE clauses) */
|
|
117
|
+
updateExpression: string;
|
|
118
|
+
/** Optional condition expression that must be satisfied */
|
|
119
|
+
conditionExpression?: string;
|
|
120
|
+
/** Map of expression attribute name placeholders to actual names */
|
|
121
|
+
expressionAttributeNames?: Record<string, string>;
|
|
122
|
+
/** Map of expression attribute value placeholders to actual values */
|
|
123
|
+
expressionAttributeValues?: DynamoItem;
|
|
124
|
+
/** Which item attributes to include in the response */
|
|
125
|
+
returnValues?: "ALL_NEW" | "UPDATED_NEW" | "ALL_OLD" | "UPDATED_OLD" | "NONE";
|
|
126
|
+
}
|
|
127
|
+
interface ConditionCheckCommandParams extends DynamoCommandWithExpressions {
|
|
128
|
+
tableName: string;
|
|
129
|
+
key: Record<string, unknown>;
|
|
130
|
+
conditionExpression: string;
|
|
131
|
+
expressionAttributeNames?: Record<string, string>;
|
|
132
|
+
expressionAttributeValues?: DynamoItem;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Base interface for all builder classes that support pagination
|
|
136
|
+
* to be used by Paginator without creating circular dependencies.
|
|
137
|
+
*/
|
|
138
|
+
interface BaseBuilderInterface<T extends DynamoItem, TConfig extends TableConfig = TableConfig, B = unknown> {
|
|
139
|
+
clone(): B;
|
|
140
|
+
limit(limit: number): B;
|
|
141
|
+
getLimit(): number | undefined;
|
|
142
|
+
startFrom(lastEvaluatedKey: DynamoItem): B;
|
|
143
|
+
execute(): Promise<ResultIterator<T, TConfig>>;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Interface for the QueryBuilder class to be used by Paginator
|
|
147
|
+
* without creating a circular dependency.
|
|
148
|
+
*/
|
|
149
|
+
interface QueryBuilderInterface<T extends DynamoItem, TConfig extends TableConfig = TableConfig> extends BaseBuilderInterface<T, TConfig, QueryBuilderInterface<T, TConfig>> {
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Interface for the ScanBuilder class to be used by Paginator
|
|
153
|
+
* without creating a circular dependency.
|
|
154
|
+
*/
|
|
155
|
+
interface ScanBuilderInterface<T extends DynamoItem, TConfig extends TableConfig = TableConfig> extends BaseBuilderInterface<T, TConfig, ScanBuilderInterface<T, TConfig>> {
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Interface for the FilterBuilder class to be used by Paginator
|
|
159
|
+
* without creating a circular dependency.
|
|
160
|
+
*/
|
|
161
|
+
interface FilterBuilderInterface<T extends DynamoItem, TConfig extends TableConfig = TableConfig> extends BaseBuilderInterface<T, TConfig, FilterBuilderInterface<T, TConfig>> {
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Represents the result of a single page query operation.
|
|
165
|
+
* This interface provides all necessary information about the current page
|
|
166
|
+
* and the availability of subsequent pages.
|
|
167
|
+
*/
|
|
168
|
+
interface PaginationResult<T> {
|
|
169
|
+
/** The items (dinosaurs, habitats, etc.) retrieved for the current page */
|
|
170
|
+
items: T[];
|
|
171
|
+
/** DynamoDB's last evaluated key, used internally for pagination */
|
|
172
|
+
lastEvaluatedKey?: DynamoItem;
|
|
173
|
+
/** Indicates whether there are more pages available */
|
|
174
|
+
hasNextPage: boolean;
|
|
175
|
+
/** The current page number (1-indexed) */
|
|
176
|
+
page: number;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Represents a single operation within a DynamoDB transaction.
|
|
180
|
+
* Each operation can be one of:
|
|
181
|
+
* - Put: Insert or replace an item
|
|
182
|
+
* - Update: Modify an existing item
|
|
183
|
+
* - Delete: Remove an item
|
|
184
|
+
* - ConditionCheck: Verify item state without modification
|
|
185
|
+
*/
|
|
186
|
+
type TransactionItem = {
|
|
187
|
+
type: "Put";
|
|
188
|
+
params: PutCommandParams;
|
|
189
|
+
} | {
|
|
190
|
+
type: "Update";
|
|
191
|
+
params: UpdateCommandParams;
|
|
192
|
+
} | {
|
|
193
|
+
type: "Delete";
|
|
194
|
+
params: DeleteCommandParams;
|
|
195
|
+
} | {
|
|
196
|
+
type: "ConditionCheck";
|
|
197
|
+
params: ConditionCheckCommandParams;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Parameters for the DynamoDB get command.
|
|
202
|
+
*/
|
|
203
|
+
interface GetCommandParams {
|
|
204
|
+
/** The name of the DynamoDB table */
|
|
205
|
+
tableName: string;
|
|
206
|
+
/** The primary key of the item to get */
|
|
207
|
+
key: PrimaryKeyWithoutExpression;
|
|
208
|
+
/** Comma-separated list of attributes to return */
|
|
209
|
+
projectionExpression?: string;
|
|
210
|
+
/** Map of expression attribute name placeholders to actual names */
|
|
211
|
+
expressionAttributeNames?: Record<string, string>;
|
|
212
|
+
/** Whether to use strongly consistent reads */
|
|
213
|
+
consistentRead?: boolean;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Function type for executing DynamoDB get operations.
|
|
217
|
+
* @typeParam T - The type of item being retrieved
|
|
218
|
+
*/
|
|
219
|
+
type GetExecutor<T extends DynamoItem> = (params: GetCommandParams) => Promise<{
|
|
220
|
+
item: T | undefined;
|
|
221
|
+
}>;
|
|
222
|
+
/**
|
|
223
|
+
* Builder for creating DynamoDB get operations.
|
|
224
|
+
* Use this builder when you need to:
|
|
225
|
+
* - Retrieve a single dinosaur by its primary key
|
|
226
|
+
* - Project specific dinosaur attributes
|
|
227
|
+
* - Use consistent reads for critical dinosaur data
|
|
228
|
+
*
|
|
229
|
+
* @example
|
|
230
|
+
* ```typescript
|
|
231
|
+
* // Simple get
|
|
232
|
+
* const result = await new GetBuilder(executor, { pk: 'dinosaur#123', sk: 'profile' })
|
|
233
|
+
* .execute();
|
|
234
|
+
*
|
|
235
|
+
* // Get with projection and consistent read
|
|
236
|
+
* const result = await new GetBuilder(executor, { pk: 'dinosaur#123', sk: 'profile' })
|
|
237
|
+
* .select(['species', 'name', 'diet'])
|
|
238
|
+
* .consistentRead()
|
|
239
|
+
* .execute();
|
|
240
|
+
* ```
|
|
241
|
+
*
|
|
242
|
+
* @typeParam T - The type of item being retrieved
|
|
243
|
+
*/
|
|
244
|
+
declare class GetBuilder<T extends DynamoItem> {
|
|
245
|
+
private readonly executor;
|
|
246
|
+
private readonly params;
|
|
247
|
+
private options;
|
|
248
|
+
private selectedFields;
|
|
249
|
+
/**
|
|
250
|
+
* Creates a new GetBuilder instance.
|
|
251
|
+
*
|
|
252
|
+
* @param executor - Function that executes the get operation
|
|
253
|
+
* @param key - Primary key of the item to retrieve
|
|
254
|
+
* @param tableName - Name of the DynamoDB table
|
|
255
|
+
*/
|
|
256
|
+
constructor(executor: GetExecutor<T>, key: PrimaryKeyWithoutExpression, tableName: string);
|
|
257
|
+
/**
|
|
258
|
+
* Specifies which attributes to return in the get results.
|
|
259
|
+
*
|
|
260
|
+
* @example
|
|
261
|
+
* ```typescript
|
|
262
|
+
* // Select single attribute
|
|
263
|
+
* builder.select('species')
|
|
264
|
+
*
|
|
265
|
+
* // Select multiple attributes
|
|
266
|
+
* builder.select(['id', 'species', 'diet'])
|
|
267
|
+
*
|
|
268
|
+
* // Chain multiple select calls
|
|
269
|
+
* builder
|
|
270
|
+
* .select('id')
|
|
271
|
+
* .select(['species', 'diet'])
|
|
272
|
+
* ```
|
|
273
|
+
*
|
|
274
|
+
* @param fields - A single field name or an array of field names to return
|
|
275
|
+
* @returns The builder instance for method chaining
|
|
276
|
+
*/
|
|
277
|
+
select<K extends Path<T>>(fields: K | K[]): GetBuilder<T>;
|
|
278
|
+
/**
|
|
279
|
+
* Sets whether to use strongly consistent reads for the get operation.
|
|
280
|
+
* Use this method when you need:
|
|
281
|
+
* - The most up-to-date dinosaur data
|
|
282
|
+
* - To ensure you're reading the latest dinosaur status
|
|
283
|
+
* - Critical safety information about dangerous species
|
|
284
|
+
*
|
|
285
|
+
* Note: Consistent reads consume twice the throughput
|
|
286
|
+
*
|
|
287
|
+
* @example
|
|
288
|
+
* ```typescript
|
|
289
|
+
* // Get the latest T-Rex data
|
|
290
|
+
* const result = await new GetBuilder(executor, { pk: 'dinosaur#123', sk: 'profile' })
|
|
291
|
+
* .consistentRead()
|
|
292
|
+
* .execute();
|
|
293
|
+
* ```
|
|
294
|
+
*
|
|
295
|
+
* @param consistentRead - Whether to use consistent reads (defaults to true)
|
|
296
|
+
* @returns The builder instance for method chaining
|
|
297
|
+
*/
|
|
298
|
+
consistentRead(consistentRead?: boolean): GetBuilder<T>;
|
|
299
|
+
/**
|
|
300
|
+
* Adds this get operation to a batch with optional entity type information.
|
|
301
|
+
*
|
|
302
|
+
* @example Basic Usage
|
|
303
|
+
* ```ts
|
|
304
|
+
* const batch = table.batchBuilder();
|
|
305
|
+
*
|
|
306
|
+
* // Add multiple get operations to batch
|
|
307
|
+
* dinosaurRepo.get({ id: 'dino-1' }).withBatch(batch);
|
|
308
|
+
* dinosaurRepo.get({ id: 'dino-2' }).withBatch(batch);
|
|
309
|
+
* dinosaurRepo.get({ id: 'dino-3' }).withBatch(batch);
|
|
310
|
+
*
|
|
311
|
+
* // Execute all gets efficiently
|
|
312
|
+
* const results = await batch.execute();
|
|
313
|
+
* ```
|
|
314
|
+
*
|
|
315
|
+
* @example Typed Usage
|
|
316
|
+
* ```ts
|
|
317
|
+
* const batch = table.batchBuilder<{
|
|
318
|
+
* User: UserEntity;
|
|
319
|
+
* Order: OrderEntity;
|
|
320
|
+
* }>();
|
|
321
|
+
*
|
|
322
|
+
* // Add operations with type information
|
|
323
|
+
* userRepo.get({ id: 'user-1' }).withBatch(batch, 'User');
|
|
324
|
+
* orderRepo.get({ id: 'order-1' }).withBatch(batch, 'Order');
|
|
325
|
+
*
|
|
326
|
+
* // Execute and get typed results
|
|
327
|
+
* const result = await batch.execute();
|
|
328
|
+
* const users: UserEntity[] = result.reads.itemsByType.User;
|
|
329
|
+
* const orders: OrderEntity[] = result.reads.itemsByType.Order;
|
|
330
|
+
* ```
|
|
331
|
+
*
|
|
332
|
+
* @param batch - The batch builder to add this operation to
|
|
333
|
+
* @param entityType - Optional entity type key for type tracking
|
|
334
|
+
*/
|
|
335
|
+
withBatch<TEntities extends Record<string, DynamoItem> = Record<string, DynamoItem>, K extends keyof TEntities = keyof TEntities>(batch: BatchBuilder<TEntities>, entityType?: K): void;
|
|
336
|
+
/**
|
|
337
|
+
* Converts the builder configuration to a DynamoDB command
|
|
338
|
+
*/
|
|
339
|
+
private toDynamoCommand;
|
|
340
|
+
/**
|
|
341
|
+
* Executes the get operation against DynamoDB.
|
|
342
|
+
*
|
|
343
|
+
* @example
|
|
344
|
+
* ```typescript
|
|
345
|
+
* try {
|
|
346
|
+
* const result = await new GetBuilder(executor, { pk: 'dinosaur#123', sk: 'profile' })
|
|
347
|
+
* .select(['species', 'name', 'diet'])
|
|
348
|
+
* .consistentRead()
|
|
349
|
+
* .execute();
|
|
350
|
+
*
|
|
351
|
+
* if (result.item) {
|
|
352
|
+
* console.log('Dinosaur found:', result.item);
|
|
353
|
+
* } else {
|
|
354
|
+
* console.log('Dinosaur not found');
|
|
355
|
+
* }
|
|
356
|
+
* } catch (error) {
|
|
357
|
+
* console.error('Error getting dinosaur:', error);
|
|
358
|
+
* }
|
|
359
|
+
* ```
|
|
360
|
+
*
|
|
361
|
+
* @returns A promise that resolves to an object containing:
|
|
362
|
+
* - item: The retrieved dinosaur or undefined if not found
|
|
363
|
+
*/
|
|
364
|
+
execute(): Promise<{
|
|
365
|
+
item: T | undefined;
|
|
366
|
+
}>;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Configuration for batch operations
|
|
371
|
+
*/
|
|
372
|
+
interface BatchConfig {
|
|
373
|
+
partitionKey: string;
|
|
374
|
+
sortKey?: string;
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Executor function for batch write operations
|
|
378
|
+
*/
|
|
379
|
+
type BatchWriteExecutor = (operations: Array<BatchWriteOperation<DynamoItem>>) => Promise<{
|
|
380
|
+
unprocessedItems: Array<BatchWriteOperation<DynamoItem>>;
|
|
381
|
+
}>;
|
|
382
|
+
/**
|
|
383
|
+
* Executor function for batch get operations
|
|
384
|
+
*/
|
|
385
|
+
type BatchGetExecutor = (keys: Array<PrimaryKeyWithoutExpression>) => Promise<{
|
|
386
|
+
items: DynamoItem[];
|
|
387
|
+
unprocessedKeys: PrimaryKeyWithoutExpression[];
|
|
388
|
+
}>;
|
|
389
|
+
/**
|
|
390
|
+
* Error class for batch operation failures
|
|
391
|
+
*/
|
|
392
|
+
declare class BatchError extends Error {
|
|
393
|
+
readonly operation: "write" | "read";
|
|
394
|
+
readonly cause?: Error;
|
|
395
|
+
constructor(message: string, operation: "write" | "read", cause?: Error);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Result structure for batch operations
|
|
399
|
+
*/
|
|
400
|
+
interface BatchResult {
|
|
401
|
+
/** Whether the batch operation completed successfully */
|
|
402
|
+
success: boolean;
|
|
403
|
+
/** Write operation results */
|
|
404
|
+
writes: {
|
|
405
|
+
/** Number of write operations processed successfully */
|
|
406
|
+
processed: number;
|
|
407
|
+
/** Write operations that were not processed and may need retry */
|
|
408
|
+
unprocessed: Array<BatchWriteOperation<DynamoItem>>;
|
|
409
|
+
};
|
|
410
|
+
/** Read operation results */
|
|
411
|
+
reads: {
|
|
412
|
+
/** Items retrieved from the batch get operations */
|
|
413
|
+
items: DynamoItem[];
|
|
414
|
+
/** Number of items found and returned */
|
|
415
|
+
found: number;
|
|
416
|
+
/** Keys that were not processed and may need retry */
|
|
417
|
+
unprocessed: PrimaryKeyWithoutExpression[];
|
|
418
|
+
};
|
|
419
|
+
/** Total number of operations in the batch */
|
|
420
|
+
totalOperations: number;
|
|
421
|
+
/** Any errors that occurred during batch processing */
|
|
422
|
+
errors?: BatchError[];
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Typed result structure for batch operations with entity type information
|
|
426
|
+
*/
|
|
427
|
+
interface TypedBatchResult<TEntities extends Record<string, DynamoItem> = Record<string, DynamoItem>> {
|
|
428
|
+
/** Whether the batch operation completed successfully */
|
|
429
|
+
success: boolean;
|
|
430
|
+
/** Write operation results */
|
|
431
|
+
writes: {
|
|
432
|
+
/** Number of write operations processed successfully */
|
|
433
|
+
processed: number;
|
|
434
|
+
/** Write operations that were not processed and may need retry */
|
|
435
|
+
unprocessed: Array<BatchWriteOperation<DynamoItem>>;
|
|
436
|
+
};
|
|
437
|
+
/** Read operation results with typed items */
|
|
438
|
+
reads: {
|
|
439
|
+
/** Items retrieved from the batch get operations, grouped by entity type */
|
|
440
|
+
itemsByType: {
|
|
441
|
+
[K in keyof TEntities]: TEntities[K][];
|
|
442
|
+
};
|
|
443
|
+
/** All items retrieved (typed as union of all entity types) */
|
|
444
|
+
items: TEntities[keyof TEntities][];
|
|
445
|
+
/** Number of items found and returned */
|
|
446
|
+
found: number;
|
|
447
|
+
/** Keys that were not processed and may need retry */
|
|
448
|
+
unprocessed: PrimaryKeyWithoutExpression[];
|
|
449
|
+
};
|
|
450
|
+
/** Total number of operations in the batch */
|
|
451
|
+
totalOperations: number;
|
|
452
|
+
/** Any errors that occurred during batch execution */
|
|
453
|
+
errors?: BatchError[];
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Builder for creating and executing DynamoDB batch operations with full entity support and type inference.
|
|
457
|
+
*
|
|
458
|
+
* Use BatchBuilder when you need to:
|
|
459
|
+
* - Perform multiple operations efficiently (up to 25 writes, 100 reads per batch)
|
|
460
|
+
* - Maintain entity validation, key generation, and type safety
|
|
461
|
+
* - Mix read and write operations in a single batch
|
|
462
|
+
* - Get typed results grouped by entity type
|
|
463
|
+
*
|
|
464
|
+
* @example Basic Usage
|
|
465
|
+
* ```typescript
|
|
466
|
+
* // Define entity types for the batch
|
|
467
|
+
* const batch = table.batchBuilder<{
|
|
468
|
+
* User: UserEntity;
|
|
469
|
+
* Order: OrderEntity;
|
|
470
|
+
* }>();
|
|
471
|
+
*
|
|
472
|
+
* // Add operations using entity repositories
|
|
473
|
+
* userRepo.create(newUser).withBatch(batch, 'User')
|
|
474
|
+
* userRepo.delete({ id: 'old-user' }).withBatch(batch, 'User')
|
|
475
|
+
* orderRepo.get({ id: 'existing-order' }).withBatch(batch, 'Order')
|
|
476
|
+
*
|
|
477
|
+
* // Execute all operations and get typed results
|
|
478
|
+
* const result = await batch.execute()
|
|
479
|
+
* const users: UserEntity[] = result.reads.itemsByType.User
|
|
480
|
+
* const orders: OrderEntity[] = result.reads.itemsByType.Order
|
|
481
|
+
* ```
|
|
482
|
+
*
|
|
483
|
+
* @example Error Handling
|
|
484
|
+
* ```typescript
|
|
485
|
+
* try {
|
|
486
|
+
* const result = await batch.execute()
|
|
487
|
+
*
|
|
488
|
+
* if (result.writes.unprocessed.length > 0) {
|
|
489
|
+
* console.warn('Some writes were not processed:', result.writes.unprocessed)
|
|
490
|
+
* }
|
|
491
|
+
* } catch (error) {
|
|
492
|
+
* if (error instanceof BatchError) {
|
|
493
|
+
* console.error('Batch operation failed:', error.message)
|
|
494
|
+
* }
|
|
495
|
+
* }
|
|
496
|
+
* ```
|
|
497
|
+
*/
|
|
498
|
+
declare class BatchBuilder<TEntities extends Record<string, DynamoItem> = Record<string, DynamoItem>> {
|
|
499
|
+
private batchWriteExecutor;
|
|
500
|
+
private batchGetExecutor;
|
|
501
|
+
private config;
|
|
502
|
+
private writeItems;
|
|
503
|
+
private getItems;
|
|
504
|
+
constructor(batchWriteExecutor: BatchWriteExecutor, batchGetExecutor: BatchGetExecutor, config: BatchConfig);
|
|
505
|
+
/**
|
|
506
|
+
* Checks if the batch is empty (contains no operations)
|
|
507
|
+
*
|
|
508
|
+
* @returns true if the batch contains no operations
|
|
509
|
+
*/
|
|
510
|
+
isEmpty(): boolean;
|
|
511
|
+
/**
|
|
512
|
+
* Gets the count of operations in the batch
|
|
513
|
+
*
|
|
514
|
+
* @returns Object containing the count of write and read operations
|
|
515
|
+
*/
|
|
516
|
+
getOperationCount(): {
|
|
517
|
+
writes: number;
|
|
518
|
+
reads: number;
|
|
519
|
+
};
|
|
520
|
+
/**
|
|
521
|
+
* Validates that the batch is not empty before execution
|
|
522
|
+
*
|
|
523
|
+
* @throws {BatchError} If the batch is empty
|
|
524
|
+
*/
|
|
525
|
+
private validateNotEmpty;
|
|
526
|
+
/**
|
|
527
|
+
* Adds a put operation to the batch with entity type information.
|
|
528
|
+
* This method is used internally by entity builders.
|
|
529
|
+
*
|
|
530
|
+
* @param command - The complete put command configuration
|
|
531
|
+
* @param entityType - The entity type name for type tracking
|
|
532
|
+
* @returns The batch builder for method chaining
|
|
533
|
+
* @internal
|
|
534
|
+
*/
|
|
535
|
+
putWithCommand<K extends keyof TEntities>(command: PutCommandParams, entityType?: K): this;
|
|
536
|
+
/**
|
|
537
|
+
* Adds a delete operation to the batch with entity type information.
|
|
538
|
+
* This method is used internally by entity builders.
|
|
539
|
+
*
|
|
540
|
+
* @param command - The complete delete command configuration
|
|
541
|
+
* @param entityType - The entity type name for type tracking
|
|
542
|
+
* @returns The batch builder for method chaining
|
|
543
|
+
* @internal
|
|
544
|
+
*/
|
|
545
|
+
deleteWithCommand<K extends keyof TEntities>(command: DeleteCommandParams, entityType?: K): this;
|
|
546
|
+
/**
|
|
547
|
+
* Adds a get operation to the batch with entity type information.
|
|
548
|
+
* This method is used internally by entity builders.
|
|
549
|
+
*
|
|
550
|
+
* @param command - The complete get command configuration
|
|
551
|
+
* @param entityType - The entity type name for type tracking
|
|
552
|
+
* @returns The batch builder for method chaining
|
|
553
|
+
* @internal
|
|
554
|
+
*/
|
|
555
|
+
getWithCommand<K extends keyof TEntities>(command: GetCommandParams, entityType?: K): this;
|
|
556
|
+
/**
|
|
557
|
+
* Executes all write operations in the batch.
|
|
558
|
+
*
|
|
559
|
+
* @returns A promise that resolves to any unprocessed operations
|
|
560
|
+
* @private
|
|
561
|
+
*/
|
|
562
|
+
private executeWrites;
|
|
563
|
+
/**
|
|
564
|
+
* Executes all get operations in the batch.
|
|
565
|
+
*
|
|
566
|
+
* @returns A promise that resolves to the retrieved items
|
|
567
|
+
* @private
|
|
568
|
+
*/
|
|
569
|
+
private executeGets;
|
|
570
|
+
/**
|
|
571
|
+
* Groups retrieved items by their entity type.
|
|
572
|
+
* @private
|
|
573
|
+
*/
|
|
574
|
+
private groupItemsByType;
|
|
575
|
+
/**
|
|
576
|
+
* Executes all operations in the batch with typed results.
|
|
577
|
+
* Performs write operations first, then get operations.
|
|
578
|
+
*
|
|
579
|
+
* @returns A promise that resolves to a TypedBatchResult with entity type information
|
|
580
|
+
* @throws {BatchError} If the batch is empty or if operations fail
|
|
581
|
+
*/
|
|
582
|
+
execute(): Promise<TypedBatchResult<TEntities>>;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Configuration options for DynamoDB transactions.
|
|
587
|
+
*/
|
|
588
|
+
interface TransactionOptions {
|
|
589
|
+
/** Unique identifier for the transaction request (idempotency token) */
|
|
590
|
+
clientRequestToken?: string;
|
|
591
|
+
/** Level of consumed capacity details to return */
|
|
592
|
+
returnConsumedCapacity?: "INDEXES" | "TOTAL" | "NONE";
|
|
593
|
+
/** Whether to return item collection metrics */
|
|
594
|
+
returnItemCollectionMetrics?: "SIZE" | "NONE";
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Configuration for table indexes used in duplicate detection.
|
|
598
|
+
* Defines the key structure for checking uniqueness constraints.
|
|
599
|
+
*/
|
|
600
|
+
interface IndexConfig {
|
|
601
|
+
/** The partition key attribute name */
|
|
602
|
+
partitionKey: string;
|
|
603
|
+
/** Optional sort key attribute name */
|
|
604
|
+
sortKey?: string;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Function type for executing DynamoDB transaction operations.
|
|
608
|
+
* @param params - The complete transaction command input
|
|
609
|
+
* @returns A promise that resolves when the transaction completes
|
|
610
|
+
*/
|
|
611
|
+
type TransactionExecutor = (params: TransactWriteCommandInput) => Promise<void>;
|
|
612
|
+
/**
|
|
613
|
+
* Builder for creating and executing DynamoDB transactions.
|
|
614
|
+
* Use this builder when you need to:
|
|
615
|
+
* - Perform multiple operations atomically
|
|
616
|
+
* - Ensure data consistency across operations
|
|
617
|
+
* - Implement complex business logic that requires atomic updates
|
|
618
|
+
* - Prevent duplicate items across tables
|
|
619
|
+
*
|
|
620
|
+
* The builder supports:
|
|
621
|
+
* - Put operations (insert/replace items)
|
|
622
|
+
* - Delete operations
|
|
623
|
+
* - Update operations
|
|
624
|
+
* - Condition checks
|
|
625
|
+
* - Duplicate detection
|
|
626
|
+
* - Transaction-wide options
|
|
627
|
+
*
|
|
628
|
+
* @example
|
|
629
|
+
* ```typescript
|
|
630
|
+
* // Create a transaction with multiple operations
|
|
631
|
+
* const transaction = new TransactionBuilder(executor, {
|
|
632
|
+
* partitionKey: 'id',
|
|
633
|
+
* sortKey: 'type'
|
|
634
|
+
* });
|
|
635
|
+
*
|
|
636
|
+
* // Add a new order
|
|
637
|
+
* transaction.put('orders', {
|
|
638
|
+
* orderId: '123',
|
|
639
|
+
* status: 'PENDING'
|
|
640
|
+
* });
|
|
641
|
+
*
|
|
642
|
+
* // Update inventory with condition
|
|
643
|
+
* transaction.update(
|
|
644
|
+
* 'inventory',
|
|
645
|
+
* { productId: 'ABC' },
|
|
646
|
+
* 'set quantity = quantity - :amount',
|
|
647
|
+
* { ':amount': 1 },
|
|
648
|
+
* op => op.gte('quantity', 1)
|
|
649
|
+
* );
|
|
650
|
+
*
|
|
651
|
+
* // Execute the transaction atomically
|
|
652
|
+
* await transaction.execute();
|
|
653
|
+
* ```
|
|
654
|
+
*
|
|
655
|
+
* Note: DynamoDB transactions have some limitations:
|
|
656
|
+
* - Maximum 25 operations per transaction
|
|
657
|
+
* - All operations must be in the same AWS region
|
|
658
|
+
* - Cannot include table scans or queries
|
|
659
|
+
*/
|
|
660
|
+
declare class TransactionBuilder {
|
|
661
|
+
private items;
|
|
662
|
+
private options;
|
|
663
|
+
private indexConfig;
|
|
664
|
+
private readonly executor;
|
|
665
|
+
constructor(executor: TransactionExecutor, indexConfig: IndexConfig);
|
|
666
|
+
/**
|
|
667
|
+
* Checks if an item with the same primary key already exists in the transaction
|
|
668
|
+
* @private
|
|
669
|
+
*/
|
|
670
|
+
private checkForDuplicateItem;
|
|
671
|
+
createKeyForPrimaryIndex(key: PrimaryKeyWithoutExpression): {
|
|
672
|
+
[x: string]: string;
|
|
673
|
+
};
|
|
674
|
+
/**
|
|
675
|
+
* Adds a put operation to the transaction.
|
|
676
|
+
*
|
|
677
|
+
* The method automatically checks for duplicate items within the transaction
|
|
678
|
+
* to prevent multiple operations on the same item.
|
|
679
|
+
*
|
|
680
|
+
* @example
|
|
681
|
+
* ```typescript
|
|
682
|
+
* // Simple put operation
|
|
683
|
+
* transaction.put('orders', {
|
|
684
|
+
* orderId: '123',
|
|
685
|
+
* status: 'PENDING',
|
|
686
|
+
* amount: 100
|
|
687
|
+
* });
|
|
688
|
+
*
|
|
689
|
+
* // Conditional put operation
|
|
690
|
+
* transaction.put(
|
|
691
|
+
* 'inventory',
|
|
692
|
+
* { productId: 'ABC', quantity: 50 },
|
|
693
|
+
* op => op.attributeNotExists('productId')
|
|
694
|
+
* );
|
|
695
|
+
*
|
|
696
|
+
* // Put with complex condition
|
|
697
|
+
* transaction.put(
|
|
698
|
+
* 'users',
|
|
699
|
+
* { userId: '123', status: 'ACTIVE' },
|
|
700
|
+
* op => op.and([
|
|
701
|
+
* op.attributeNotExists('userId'),
|
|
702
|
+
* op.beginsWith('status', 'ACTIVE')
|
|
703
|
+
* ])
|
|
704
|
+
* );
|
|
705
|
+
* ```
|
|
706
|
+
*
|
|
707
|
+
* @param tableName - The name of the DynamoDB table
|
|
708
|
+
* @param item - The item to put into the table
|
|
709
|
+
* @param condition - Optional condition that must be satisfied
|
|
710
|
+
* @returns The transaction builder for method chaining
|
|
711
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
712
|
+
*/
|
|
713
|
+
put<T extends DynamoItem>(tableName: string, item: T, condition?: Condition): this;
|
|
714
|
+
/**
|
|
715
|
+
* Adds a pre-configured put operation to the transaction.
|
|
716
|
+
*
|
|
717
|
+
* This method is particularly useful when working with PutBuilder
|
|
718
|
+
* to maintain consistency in put operations across your application.
|
|
719
|
+
*
|
|
720
|
+
* @example
|
|
721
|
+
* ```typescript
|
|
722
|
+
* // Create a put command with PutBuilder
|
|
723
|
+
* const putCommand = new PutBuilder(executor, newItem, 'users')
|
|
724
|
+
* .condition(op => op.attributeNotExists('userId'))
|
|
725
|
+
* .toDynamoCommand();
|
|
726
|
+
*
|
|
727
|
+
* // Add the command to the transaction
|
|
728
|
+
* transaction.putWithCommand(putCommand);
|
|
729
|
+
* ```
|
|
730
|
+
*
|
|
731
|
+
* @param command - The complete put command configuration
|
|
732
|
+
* @returns The transaction builder for method chaining
|
|
733
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
734
|
+
* @see PutBuilder for creating put commands
|
|
735
|
+
*/
|
|
736
|
+
putWithCommand(command: PutCommandParams): TransactionBuilder;
|
|
737
|
+
/**
|
|
738
|
+
* Adds a delete operation to the transaction.
|
|
739
|
+
*
|
|
740
|
+
* The method automatically checks for duplicate items within the transaction
|
|
741
|
+
* to prevent multiple operations on the same item.
|
|
742
|
+
*
|
|
743
|
+
* @example
|
|
744
|
+
* ```typescript
|
|
745
|
+
* // Simple delete operation
|
|
746
|
+
* transaction.delete('orders', {
|
|
747
|
+
* pk: 'ORDER#123',
|
|
748
|
+
* sk: 'METADATA'
|
|
749
|
+
* });
|
|
750
|
+
*
|
|
751
|
+
* // Conditional delete operation
|
|
752
|
+
* transaction.delete(
|
|
753
|
+
* 'users',
|
|
754
|
+
* { pk: 'USER#123' },
|
|
755
|
+
* op => op.eq('status', 'INACTIVE')
|
|
756
|
+
* );
|
|
757
|
+
*
|
|
758
|
+
* // Delete with complex condition
|
|
759
|
+
* transaction.delete(
|
|
760
|
+
* 'products',
|
|
761
|
+
* { pk: 'PROD#ABC' },
|
|
762
|
+
* op => op.and([
|
|
763
|
+
* op.eq('status', 'DRAFT'),
|
|
764
|
+
* op.lt('version', 5)
|
|
765
|
+
* ])
|
|
766
|
+
* );
|
|
767
|
+
* ```
|
|
768
|
+
*
|
|
769
|
+
* @param tableName - The name of the DynamoDB table
|
|
770
|
+
* @param key - The primary key of the item to delete
|
|
771
|
+
* @param condition - Optional condition that must be satisfied
|
|
772
|
+
* @returns The transaction builder for method chaining
|
|
773
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
774
|
+
*/
|
|
775
|
+
delete(tableName: string, key: PrimaryKeyWithoutExpression, condition?: Condition): TransactionBuilder;
|
|
776
|
+
/**
|
|
777
|
+
* Adds a pre-configured delete operation to the transaction.
|
|
778
|
+
*
|
|
779
|
+
* This method is particularly useful when working with DeleteBuilder
|
|
780
|
+
* to maintain consistency in delete operations across your application.
|
|
781
|
+
*
|
|
782
|
+
* @example
|
|
783
|
+
* ```typescript
|
|
784
|
+
* // Create a delete command with DeleteBuilder
|
|
785
|
+
* const deleteCommand = new DeleteBuilder(executor, 'users', { pk: 'USER#123' })
|
|
786
|
+
* .condition(op => op.and([
|
|
787
|
+
* op.attributeExists('pk'),
|
|
788
|
+
* op.eq('status', 'INACTIVE')
|
|
789
|
+
* ]))
|
|
790
|
+
* .toDynamoCommand();
|
|
791
|
+
*
|
|
792
|
+
* // Add the command to the transaction
|
|
793
|
+
* transaction.deleteWithCommand(deleteCommand);
|
|
794
|
+
* ```
|
|
795
|
+
*
|
|
796
|
+
* @param command - The complete delete command configuration
|
|
797
|
+
* @returns The transaction builder for method chaining
|
|
798
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
799
|
+
* @see DeleteBuilder for creating delete commands
|
|
800
|
+
*/
|
|
801
|
+
deleteWithCommand(command: DeleteCommandParams): this;
|
|
802
|
+
/**
|
|
803
|
+
* Adds an update operation to the transaction.
|
|
804
|
+
*
|
|
805
|
+
* The method supports all DynamoDB update expressions:
|
|
806
|
+
* - SET: Modify or add attributes
|
|
807
|
+
* - REMOVE: Delete attributes
|
|
808
|
+
* - ADD: Update numbers and sets
|
|
809
|
+
* - DELETE: Remove elements from a set
|
|
810
|
+
*
|
|
811
|
+
* @example
|
|
812
|
+
* ```typescript
|
|
813
|
+
* // Simple update
|
|
814
|
+
* transaction.update(
|
|
815
|
+
* 'orders',
|
|
816
|
+
* { pk: 'ORDER#123' },
|
|
817
|
+
* 'SET #status = :status',
|
|
818
|
+
* { '#status': 'status' },
|
|
819
|
+
* { ':status': 'PROCESSING' }
|
|
820
|
+
* );
|
|
821
|
+
*
|
|
822
|
+
* // Complex update with multiple operations
|
|
823
|
+
* transaction.update(
|
|
824
|
+
* 'products',
|
|
825
|
+
* { pk: 'PROD#ABC' },
|
|
826
|
+
* 'SET #qty = #qty - :amount, #status = :status REMOVE #oldAttr',
|
|
827
|
+
* { '#qty': 'quantity', '#status': 'status', '#oldAttr': 'deprecated_field' },
|
|
828
|
+
* { ':amount': 1, ':status': 'LOW_STOCK' }
|
|
829
|
+
* );
|
|
830
|
+
*
|
|
831
|
+
* // Conditional update
|
|
832
|
+
* transaction.update(
|
|
833
|
+
* 'users',
|
|
834
|
+
* { pk: 'USER#123' },
|
|
835
|
+
* 'SET #lastLogin = :now',
|
|
836
|
+
* { '#lastLogin': 'lastLoginDate' },
|
|
837
|
+
* { ':now': new Date().toISOString() },
|
|
838
|
+
* op => op.attributeExists('pk')
|
|
839
|
+
* );
|
|
840
|
+
* ```
|
|
841
|
+
*
|
|
842
|
+
* @param tableName - The name of the DynamoDB table
|
|
843
|
+
* @param key - The primary key of the item to update
|
|
844
|
+
* @param updateExpression - The update expression (SET, REMOVE, ADD, DELETE)
|
|
845
|
+
* @param expressionAttributeNames - Map of attribute name placeholders to actual names
|
|
846
|
+
* @param expressionAttributeValues - Map of value placeholders to actual values
|
|
847
|
+
* @param condition - Optional condition that must be satisfied
|
|
848
|
+
* @returns The transaction builder for method chaining
|
|
849
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
850
|
+
*/
|
|
851
|
+
update<T extends DynamoItem>(tableName: string, key: PrimaryKeyWithoutExpression, updateExpression: string, expressionAttributeNames?: Record<string, string>, expressionAttributeValues?: Record<string, unknown>, condition?: Condition): this;
|
|
852
|
+
/**
|
|
853
|
+
* Adds a pre-configured update operation to the transaction.
|
|
854
|
+
*
|
|
855
|
+
* This method is particularly useful when working with UpdateBuilder
|
|
856
|
+
* to maintain consistency in update operations across your application.
|
|
857
|
+
*
|
|
858
|
+
* @example
|
|
859
|
+
* ```typescript
|
|
860
|
+
* // Create an update command with UpdateBuilder
|
|
861
|
+
* const updateCommand = new UpdateBuilder(executor, 'inventory', { pk: 'PROD#ABC' })
|
|
862
|
+
* .set('quantity', ':qty')
|
|
863
|
+
* .set('lastUpdated', ':now')
|
|
864
|
+
* .values({
|
|
865
|
+
* ':qty': 100,
|
|
866
|
+
* ':now': new Date().toISOString()
|
|
867
|
+
* })
|
|
868
|
+
* .condition(op => op.gt('quantity', 0))
|
|
869
|
+
* .toDynamoCommand();
|
|
870
|
+
*
|
|
871
|
+
* // Add the command to the transaction
|
|
872
|
+
* transaction.updateWithCommand(updateCommand);
|
|
873
|
+
* ```
|
|
874
|
+
*
|
|
875
|
+
* @param command - The complete update command configuration
|
|
876
|
+
* @returns The transaction builder for method chaining
|
|
877
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
878
|
+
* @see UpdateBuilder for creating update commands
|
|
879
|
+
*/
|
|
880
|
+
updateWithCommand(command: UpdateCommandParams): TransactionBuilder;
|
|
881
|
+
/**
|
|
882
|
+
* Adds a condition check operation to the transaction.
|
|
883
|
+
*
|
|
884
|
+
* Condition checks are particularly useful for:
|
|
885
|
+
* - Implementing optimistic locking
|
|
886
|
+
* - Ensuring referential integrity
|
|
887
|
+
* - Validating business rules atomically
|
|
888
|
+
*
|
|
889
|
+
* @example
|
|
890
|
+
* ```typescript
|
|
891
|
+
* // Check if order is in correct state
|
|
892
|
+
* transaction.conditionCheck(
|
|
893
|
+
* 'orders',
|
|
894
|
+
* { pk: 'ORDER#123' },
|
|
895
|
+
* op => op.eq('status', 'PENDING')
|
|
896
|
+
* );
|
|
897
|
+
*
|
|
898
|
+
* // Complex condition check
|
|
899
|
+
* transaction.conditionCheck(
|
|
900
|
+
* 'inventory',
|
|
901
|
+
* { pk: 'PROD#ABC' },
|
|
902
|
+
* op => op.and([
|
|
903
|
+
* op.gt('quantity', 0),
|
|
904
|
+
* op.eq('status', 'ACTIVE'),
|
|
905
|
+
* op.attributeExists('lastRestockDate')
|
|
906
|
+
* ])
|
|
907
|
+
* );
|
|
908
|
+
*
|
|
909
|
+
* // Check with multiple attributes
|
|
910
|
+
* transaction.conditionCheck(
|
|
911
|
+
* 'users',
|
|
912
|
+
* { pk: 'USER#123' },
|
|
913
|
+
* op => op.or([
|
|
914
|
+
* op.eq('status', 'PREMIUM'),
|
|
915
|
+
* op.gte('credits', 100)
|
|
916
|
+
* ])
|
|
917
|
+
* );
|
|
918
|
+
* ```
|
|
919
|
+
*
|
|
920
|
+
* @param tableName - The name of the DynamoDB table
|
|
921
|
+
* @param key - The primary key of the item to check
|
|
922
|
+
* @param condition - The condition that must be satisfied
|
|
923
|
+
* @returns The transaction builder for method chaining
|
|
924
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
925
|
+
* @throws {Error} If condition expression generation fails
|
|
926
|
+
*/
|
|
927
|
+
conditionCheck(tableName: string, key: PrimaryKeyWithoutExpression, condition: Condition): TransactionBuilder;
|
|
928
|
+
/**
|
|
929
|
+
* Adds a pre-configured condition check operation to the transaction.
|
|
930
|
+
*
|
|
931
|
+
* This method is particularly useful when working with ConditionCheckBuilder
|
|
932
|
+
* to maintain consistency in condition checks across your application.
|
|
933
|
+
*
|
|
934
|
+
* @example
|
|
935
|
+
* ```typescript
|
|
936
|
+
* // Create a condition check with ConditionCheckBuilder
|
|
937
|
+
* const checkCommand = new ConditionCheckBuilder('inventory', { pk: 'PROD#ABC' })
|
|
938
|
+
* .condition(op => op.and([
|
|
939
|
+
* op.between('quantity', 10, 100),
|
|
940
|
+
* op.beginsWith('category', 'ELECTRONICS'),
|
|
941
|
+
* op.attributeExists('lastAuditDate')
|
|
942
|
+
* ]))
|
|
943
|
+
* .toDynamoCommand();
|
|
944
|
+
*
|
|
945
|
+
* // Add the command to the transaction
|
|
946
|
+
* transaction.conditionCheckWithCommand(checkCommand);
|
|
947
|
+
* ```
|
|
948
|
+
*
|
|
949
|
+
* @param command - The complete condition check command configuration
|
|
950
|
+
* @returns The transaction builder for method chaining
|
|
951
|
+
* @throws {Error} If a duplicate item is detected in the transaction
|
|
952
|
+
* @see ConditionCheckBuilder for creating condition check commands
|
|
953
|
+
*/
|
|
954
|
+
conditionCheckWithCommand(command: ConditionCheckCommandParams): TransactionBuilder;
|
|
955
|
+
/**
|
|
956
|
+
* Sets options for the transaction execution.
|
|
957
|
+
*
|
|
958
|
+
* @example
|
|
959
|
+
* ```typescript
|
|
960
|
+
* // Enable idempotency and capacity tracking
|
|
961
|
+
* transaction.withOptions({
|
|
962
|
+
* clientRequestToken: 'unique-request-id-123',
|
|
963
|
+
* returnConsumedCapacity: 'TOTAL'
|
|
964
|
+
* });
|
|
965
|
+
*
|
|
966
|
+
* // Track item collection metrics
|
|
967
|
+
* transaction.withOptions({
|
|
968
|
+
* returnItemCollectionMetrics: 'SIZE'
|
|
969
|
+
* });
|
|
970
|
+
* ```
|
|
971
|
+
*
|
|
972
|
+
* Note: ClientRequestToken can be used to make transactions idempotent,
|
|
973
|
+
* ensuring the same transaction is not executed multiple times.
|
|
974
|
+
*
|
|
975
|
+
* @param options - Configuration options for the transaction
|
|
976
|
+
* @returns The transaction builder for method chaining
|
|
977
|
+
*/
|
|
978
|
+
withOptions(options: TransactionOptions): TransactionBuilder;
|
|
979
|
+
/**
|
|
980
|
+
* Gets a human-readable representation of the transaction items.
|
|
981
|
+
*
|
|
982
|
+
* The method resolves all expression placeholders with their actual values,
|
|
983
|
+
* making it easier to understand the transaction's operations.
|
|
984
|
+
*
|
|
985
|
+
* @example
|
|
986
|
+
* ```typescript
|
|
987
|
+
* // Add multiple operations
|
|
988
|
+
* transaction
|
|
989
|
+
* .put('orders', { orderId: '123', status: 'PENDING' })
|
|
990
|
+
* .update('inventory',
|
|
991
|
+
* { productId: 'ABC' },
|
|
992
|
+
* 'SET quantity = quantity - :amount',
|
|
993
|
+
* undefined,
|
|
994
|
+
* { ':amount': 1 }
|
|
995
|
+
* );
|
|
996
|
+
*
|
|
997
|
+
* // Debug the transaction
|
|
998
|
+
* const debugInfo = transaction.debug();
|
|
999
|
+
* console.log('Transaction operations:', debugInfo);
|
|
1000
|
+
* ```
|
|
1001
|
+
*
|
|
1002
|
+
* @returns An array of readable representations of the transaction items
|
|
1003
|
+
*/
|
|
1004
|
+
debug(): Record<string, unknown>[];
|
|
1005
|
+
/**
|
|
1006
|
+
* Executes all operations in the transaction atomically.
|
|
1007
|
+
*
|
|
1008
|
+
* The transaction will only succeed if all operations succeed.
|
|
1009
|
+
* If any operation fails, the entire transaction is rolled back.
|
|
1010
|
+
*
|
|
1011
|
+
* @example
|
|
1012
|
+
* ```typescript
|
|
1013
|
+
* try {
|
|
1014
|
+
* // Build and execute transaction
|
|
1015
|
+
* await transaction
|
|
1016
|
+
* .put('orders', newOrder)
|
|
1017
|
+
* .update('inventory',
|
|
1018
|
+
* { productId: 'ABC' },
|
|
1019
|
+
* 'SET quantity = quantity - :qty',
|
|
1020
|
+
* undefined,
|
|
1021
|
+
* { ':qty': 1 }
|
|
1022
|
+
* )
|
|
1023
|
+
* .conditionCheck('products',
|
|
1024
|
+
* { productId: 'ABC' },
|
|
1025
|
+
* op => op.eq('status', 'ACTIVE')
|
|
1026
|
+
* )
|
|
1027
|
+
* .execute();
|
|
1028
|
+
*
|
|
1029
|
+
* console.log('Transaction completed successfully');
|
|
1030
|
+
* } catch (error) {
|
|
1031
|
+
* // Handle transaction failure
|
|
1032
|
+
* console.error('Transaction failed:', error);
|
|
1033
|
+
* }
|
|
1034
|
+
* ```
|
|
1035
|
+
*
|
|
1036
|
+
* @throws {Error} If no transaction items are specified
|
|
1037
|
+
* @throws {Error} If any operation in the transaction fails
|
|
1038
|
+
* @returns A promise that resolves when the transaction completes
|
|
1039
|
+
*/
|
|
1040
|
+
execute(): Promise<void>;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
interface DeleteOptions {
|
|
1044
|
+
condition?: Condition;
|
|
1045
|
+
returnValues?: "ALL_OLD";
|
|
1046
|
+
}
|
|
1047
|
+
type DeleteExecutor = (params: DeleteCommandParams) => Promise<{
|
|
1048
|
+
item?: DynamoItem;
|
|
1049
|
+
}>;
|
|
1050
|
+
/**
|
|
1051
|
+
* Builder for creating DynamoDB delete operations.
|
|
1052
|
+
*
|
|
1053
|
+
* @example
|
|
1054
|
+
* ```typescript
|
|
1055
|
+
* // Simple delete
|
|
1056
|
+
* const result = await new DeleteBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
|
|
1057
|
+
* .execute();
|
|
1058
|
+
*
|
|
1059
|
+
* // Conditional delete with old value retrieval
|
|
1060
|
+
* const result = await new DeleteBuilder(executor, 'habitats', { id: 'PADDOCK-A' })
|
|
1061
|
+
* .condition(op =>
|
|
1062
|
+
* op.and([
|
|
1063
|
+
* op.eq('status', 'DECOMMISSIONED'),
|
|
1064
|
+
* op.eq('occupants', 0),
|
|
1065
|
+
* op.lt('securityIncidents', 1)
|
|
1066
|
+
* ])
|
|
1067
|
+
* )
|
|
1068
|
+
* .returnValues('ALL_OLD')
|
|
1069
|
+
* .execute();
|
|
1070
|
+
* ```
|
|
1071
|
+
*/
|
|
1072
|
+
declare class DeleteBuilder {
|
|
1073
|
+
private options;
|
|
1074
|
+
private readonly executor;
|
|
1075
|
+
private readonly tableName;
|
|
1076
|
+
private readonly key;
|
|
1077
|
+
constructor(executor: DeleteExecutor, tableName: string, key: PrimaryKeyWithoutExpression);
|
|
1078
|
+
/**
|
|
1079
|
+
* Adds a condition that must be satisfied for the delete operation to succeed.
|
|
1080
|
+
*
|
|
1081
|
+
* @example
|
|
1082
|
+
* ```typescript
|
|
1083
|
+
* // Ensure dinosaur can be safely removed
|
|
1084
|
+
* builder.condition(op =>
|
|
1085
|
+
* op.and([
|
|
1086
|
+
* op.eq('status', 'SEDATED'),
|
|
1087
|
+
* op.eq('location', 'MEDICAL_BAY'),
|
|
1088
|
+
* op.attributeExists('lastCheckup')
|
|
1089
|
+
* ])
|
|
1090
|
+
* );
|
|
1091
|
+
*
|
|
1092
|
+
* // Verify habitat is empty
|
|
1093
|
+
* builder.condition(op =>
|
|
1094
|
+
* op.and([
|
|
1095
|
+
* op.eq('occupants', 0),
|
|
1096
|
+
* op.eq('maintenanceStatus', 'COMPLETE'),
|
|
1097
|
+
* op.not(op.attributeExists('activeAlerts'))
|
|
1098
|
+
* ])
|
|
1099
|
+
* );
|
|
1100
|
+
* ```
|
|
1101
|
+
*
|
|
1102
|
+
* @param condition - Either a Condition object or a callback function that builds the condition
|
|
1103
|
+
* @returns The builder instance for method chaining
|
|
1104
|
+
*/
|
|
1105
|
+
condition<T extends DynamoItem>(condition: Condition | ((op: ConditionOperator<T>) => Condition)): DeleteBuilder;
|
|
1106
|
+
/**
|
|
1107
|
+
* Sets whether to return the item's attribute values before deletion.
|
|
1108
|
+
*
|
|
1109
|
+
* @example
|
|
1110
|
+
* ```ts
|
|
1111
|
+
* // Archive dinosaur data before removal
|
|
1112
|
+
* const result = await builder
|
|
1113
|
+
* .returnValues('ALL_OLD')
|
|
1114
|
+
* .execute();
|
|
1115
|
+
*
|
|
1116
|
+
* if (result.item) {
|
|
1117
|
+
* console.log('Removed dinosaur data:', {
|
|
1118
|
+
* species: result.item.species,
|
|
1119
|
+
* age: result.item.age,
|
|
1120
|
+
* lastLocation: result.item.location
|
|
1121
|
+
* });
|
|
1122
|
+
* }
|
|
1123
|
+
* ```
|
|
1124
|
+
*
|
|
1125
|
+
* @param returnValues - Use 'ALL_OLD' to return all attributes of the deleted item
|
|
1126
|
+
* @returns The builder instance for method chaining
|
|
1127
|
+
*/
|
|
1128
|
+
returnValues(returnValues: "ALL_OLD"): DeleteBuilder;
|
|
1129
|
+
/**
|
|
1130
|
+
* Generate the DynamoDB command parameters
|
|
1131
|
+
*/
|
|
1132
|
+
private toDynamoCommand;
|
|
1133
|
+
/**
|
|
1134
|
+
* Adds this delete operation to a transaction.
|
|
1135
|
+
*
|
|
1136
|
+
* @example
|
|
1137
|
+
* ```ts
|
|
1138
|
+
* const transaction = new TransactionBuilder();
|
|
1139
|
+
*
|
|
1140
|
+
* // Remove dinosaur from old habitat
|
|
1141
|
+
* new DeleteBuilder(executor, 'dinosaurs', { id: 'RAPTOR-001' })
|
|
1142
|
+
* .condition(op => op.eq('status', 'SEDATED'))
|
|
1143
|
+
* .withTransaction(transaction);
|
|
1144
|
+
*
|
|
1145
|
+
* // Update old habitat occupancy
|
|
1146
|
+
* new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-A' })
|
|
1147
|
+
* .add('occupants', -1)
|
|
1148
|
+
* .withTransaction(transaction);
|
|
1149
|
+
*
|
|
1150
|
+
* // Execute transfer atomically
|
|
1151
|
+
* await transaction.execute();
|
|
1152
|
+
* ```
|
|
1153
|
+
*
|
|
1154
|
+
* @param transaction - The transaction builder to add this operation to
|
|
1155
|
+
*/
|
|
1156
|
+
withTransaction(transaction: TransactionBuilder): void;
|
|
1157
|
+
/**
|
|
1158
|
+
* Adds this delete operation to a batch with optional entity type information.
|
|
1159
|
+
*
|
|
1160
|
+
* @example Basic Usage
|
|
1161
|
+
* ```ts
|
|
1162
|
+
* const batch = table.batchBuilder();
|
|
1163
|
+
*
|
|
1164
|
+
* // Remove multiple dinosaurs in batch
|
|
1165
|
+
* dinosaurRepo.delete({ id: 'old-dino-1' }).withBatch(batch);
|
|
1166
|
+
* dinosaurRepo.delete({ id: 'old-dino-2' }).withBatch(batch);
|
|
1167
|
+
* dinosaurRepo.delete({ id: 'old-dino-3' }).withBatch(batch);
|
|
1168
|
+
*
|
|
1169
|
+
* // Execute all deletions efficiently
|
|
1170
|
+
* await batch.execute();
|
|
1171
|
+
* ```
|
|
1172
|
+
*
|
|
1173
|
+
* @example Typed Usage
|
|
1174
|
+
* ```ts
|
|
1175
|
+
* const batch = table.batchBuilder<{
|
|
1176
|
+
* User: UserEntity;
|
|
1177
|
+
* Order: OrderEntity;
|
|
1178
|
+
* }>();
|
|
1179
|
+
*
|
|
1180
|
+
* // Add operations with type information
|
|
1181
|
+
* userRepo.delete({ id: 'user-1' }).withBatch(batch, 'User');
|
|
1182
|
+
* orderRepo.delete({ id: 'order-1' }).withBatch(batch, 'Order');
|
|
1183
|
+
*
|
|
1184
|
+
* // Execute batch operations
|
|
1185
|
+
* await batch.execute();
|
|
1186
|
+
* ```
|
|
1187
|
+
*
|
|
1188
|
+
* @param batch - The batch builder to add this operation to
|
|
1189
|
+
* @param entityType - Optional entity type key for type tracking
|
|
1190
|
+
*/
|
|
1191
|
+
withBatch<TEntities extends Record<string, DynamoItem> = Record<string, DynamoItem>, K extends keyof TEntities = keyof TEntities>(batch: BatchBuilder<TEntities>, entityType?: K): void;
|
|
1192
|
+
/**
|
|
1193
|
+
* Executes the delete operation against DynamoDB.
|
|
1194
|
+
*
|
|
1195
|
+
* @example
|
|
1196
|
+
* ```ts
|
|
1197
|
+
* // Delete with condition and retrieve old values
|
|
1198
|
+
* const result = await new DeleteBuilder(executor, 'myTable', { id: '123' })
|
|
1199
|
+
* .condition(op => op.eq('status', 'INACTIVE'))
|
|
1200
|
+
* .returnValues('ALL_OLD')
|
|
1201
|
+
* .execute();
|
|
1202
|
+
*
|
|
1203
|
+
* if (result.item) {
|
|
1204
|
+
* console.log('Deleted item:', result.item);
|
|
1205
|
+
* }
|
|
1206
|
+
* ```
|
|
1207
|
+
*
|
|
1208
|
+
* @returns A promise that resolves to an object containing the deleted item's attributes (if returnValues is 'ALL_OLD')
|
|
1209
|
+
*/
|
|
1210
|
+
execute(): Promise<{
|
|
1211
|
+
item?: DynamoItem;
|
|
1212
|
+
}>;
|
|
1213
|
+
/**
|
|
1214
|
+
* Gets a human-readable representation of the delete command
|
|
1215
|
+
* with all expression placeholders replaced by their actual values.
|
|
1216
|
+
*
|
|
1217
|
+
* @example
|
|
1218
|
+
* ```ts
|
|
1219
|
+
* const debugInfo = new DeleteBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
|
|
1220
|
+
* .condition(op => op.and([
|
|
1221
|
+
* op.eq('status', 'SEDATED'),
|
|
1222
|
+
* op.eq('location', 'MEDICAL_BAY'),
|
|
1223
|
+
* op.gt('sedationLevel', 8)
|
|
1224
|
+
* op.eq('version', 1),
|
|
1225
|
+
* op.attributeExists('status')
|
|
1226
|
+
* ]))
|
|
1227
|
+
* .debug();
|
|
1228
|
+
*
|
|
1229
|
+
* console.log('Delete command:', debugInfo);
|
|
1230
|
+
* ```
|
|
1231
|
+
*
|
|
1232
|
+
* @returns A readable representation of the delete command with resolved expressions
|
|
1233
|
+
*/
|
|
1234
|
+
debug(): {
|
|
1235
|
+
raw: DeleteCommandParams;
|
|
1236
|
+
readable: {
|
|
1237
|
+
conditionExpression?: string;
|
|
1238
|
+
updateExpression?: string;
|
|
1239
|
+
filterExpression?: string;
|
|
1240
|
+
keyConditionExpression?: string;
|
|
1241
|
+
projectionExpression?: string;
|
|
1242
|
+
};
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/**
|
|
1247
|
+
* Configuration options for DynamoDB put operations.
|
|
1248
|
+
*/
|
|
1249
|
+
interface PutOptions {
|
|
1250
|
+
/** Optional condition that must be satisfied for the put operation to succeed */
|
|
1251
|
+
condition?: Condition;
|
|
1252
|
+
/** Determines how to handle the return value of the put operation
|
|
1253
|
+
* @options
|
|
1254
|
+
* - NONE: No return value
|
|
1255
|
+
* - ALL_OLD: Returns the item's previous state if it existed
|
|
1256
|
+
* - CONSISTENT: Performs a GET operation after the put to retrieve the item's new state
|
|
1257
|
+
* - INPUT: Returns the input values that were passed to the operation
|
|
1258
|
+
*/
|
|
1259
|
+
returnValues?: "ALL_OLD" | "NONE" | "CONSISTENT" | "INPUT";
|
|
1260
|
+
}
|
|
1261
|
+
type PutExecutor<T extends DynamoItem> = (params: PutCommandParams) => Promise<T>;
|
|
1262
|
+
/**
|
|
1263
|
+
* Builder for creating DynamoDB put operations.
|
|
1264
|
+
*
|
|
1265
|
+
* @example
|
|
1266
|
+
* ```typescript
|
|
1267
|
+
* // Add new dinosaur
|
|
1268
|
+
* const result = await new PutBuilder(executor, {
|
|
1269
|
+
* id: 'RAPTOR-001',
|
|
1270
|
+
* species: 'Velociraptor',
|
|
1271
|
+
* status: 'ACTIVE',
|
|
1272
|
+
* stats: {
|
|
1273
|
+
* health: 100,
|
|
1274
|
+
* age: 5,
|
|
1275
|
+
* threatLevel: 8
|
|
1276
|
+
* }
|
|
1277
|
+
* }, 'dinosaurs').execute();
|
|
1278
|
+
*
|
|
1279
|
+
* // Create new habitat with conditions
|
|
1280
|
+
* const result = await new PutBuilder(executor, {
|
|
1281
|
+
* id: 'PADDOCK-C',
|
|
1282
|
+
* type: 'CARNIVORE',
|
|
1283
|
+
* securityLevel: 'MAXIMUM',
|
|
1284
|
+
* capacity: 3,
|
|
1285
|
+
* environmentType: 'TROPICAL'
|
|
1286
|
+
* }, 'habitats')
|
|
1287
|
+
* .condition(op => op.attributeNotExists('id'))
|
|
1288
|
+
* .execute();
|
|
1289
|
+
* ```
|
|
1290
|
+
*
|
|
1291
|
+
* @typeParam T - The type of item being put into the table
|
|
1292
|
+
*/
|
|
1293
|
+
declare class PutBuilder<T extends DynamoItem> {
|
|
1294
|
+
private readonly item;
|
|
1295
|
+
private options;
|
|
1296
|
+
private readonly executor;
|
|
1297
|
+
private readonly tableName;
|
|
1298
|
+
constructor(executor: PutExecutor<T>, item: T, tableName: string);
|
|
1299
|
+
/**
|
|
1300
|
+
* Sets multiple attributes of an item using an DynamoItem.
|
|
1301
|
+
*
|
|
1302
|
+
* @example
|
|
1303
|
+
* ```typescript
|
|
1304
|
+
* // Update multiple attributes
|
|
1305
|
+
* builder.set({
|
|
1306
|
+
* species: 'Tyrannosaurus Rex',
|
|
1307
|
+
* height: 20,
|
|
1308
|
+
* diet: 'CARNIVORE',
|
|
1309
|
+
* 'stats.threatLevel': 10
|
|
1310
|
+
* });
|
|
1311
|
+
* ```
|
|
1312
|
+
*/
|
|
1313
|
+
set(values: Partial<T>): this;
|
|
1314
|
+
/**
|
|
1315
|
+
* Sets a single attribute to a specific value.
|
|
1316
|
+
*
|
|
1317
|
+
* @example
|
|
1318
|
+
* ```typescript
|
|
1319
|
+
* // Set simple attributes
|
|
1320
|
+
* builder
|
|
1321
|
+
* .set('status', 'SLEEPING')
|
|
1322
|
+
* .set('lastFeeding', new Date().toISOString());
|
|
1323
|
+
*
|
|
1324
|
+
* // Set nested attributes
|
|
1325
|
+
* builder
|
|
1326
|
+
* .set('location.zone', 'RESTRICTED')
|
|
1327
|
+
* .set('stats.health', 100);
|
|
1328
|
+
* ```
|
|
1329
|
+
*/
|
|
1330
|
+
set<K extends Path<T>>(path: K, value: PathType<T, K>): this;
|
|
1331
|
+
/**
|
|
1332
|
+
* Adds a condition that must be satisfied for the put operation to succeed.
|
|
1333
|
+
*
|
|
1334
|
+
* @example
|
|
1335
|
+
* ```ts
|
|
1336
|
+
* // Ensure item doesn't exist (insert only)
|
|
1337
|
+
* builder.condition(op => op.attributeNotExists('id'))
|
|
1338
|
+
*
|
|
1339
|
+
* // Complex condition with version check
|
|
1340
|
+
* builder.condition(op =>
|
|
1341
|
+
* op.and([
|
|
1342
|
+
* op.attributeExists('id'),
|
|
1343
|
+
* op.eq('version', currentVersion),
|
|
1344
|
+
* op.eq('status', 'ACTIVE')
|
|
1345
|
+
* ])
|
|
1346
|
+
* )
|
|
1347
|
+
* ```
|
|
1348
|
+
*
|
|
1349
|
+
* @param condition - Either a Condition object or a callback function that builds the condition
|
|
1350
|
+
* @returns The builder instance for method chaining
|
|
1351
|
+
*/
|
|
1352
|
+
/**
|
|
1353
|
+
* Adds a condition that must be satisfied for the put operation to succeed.
|
|
1354
|
+
*
|
|
1355
|
+
* @example
|
|
1356
|
+
* ```typescript
|
|
1357
|
+
* // Ensure unique dinosaur ID
|
|
1358
|
+
* builder.condition(op =>
|
|
1359
|
+
* op.attributeNotExists('id')
|
|
1360
|
+
* );
|
|
1361
|
+
*
|
|
1362
|
+
* // Verify habitat requirements
|
|
1363
|
+
* builder.condition(op =>
|
|
1364
|
+
* op.and([
|
|
1365
|
+
* op.eq('securityStatus', 'READY'),
|
|
1366
|
+
* op.attributeExists('lastInspection'),
|
|
1367
|
+
* op.gt('securityLevel', 5)
|
|
1368
|
+
* ])
|
|
1369
|
+
* );
|
|
1370
|
+
*
|
|
1371
|
+
* // Check breeding facility conditions
|
|
1372
|
+
* builder.condition(op =>
|
|
1373
|
+
* op.and([
|
|
1374
|
+
* op.between('temperature', 25, 30),
|
|
1375
|
+
* op.between('humidity', 60, 80),
|
|
1376
|
+
* op.eq('quarantineStatus', 'CLEAR')
|
|
1377
|
+
* ])
|
|
1378
|
+
* );
|
|
1379
|
+
* ```
|
|
1380
|
+
*
|
|
1381
|
+
* @param condition - Either a Condition object or a callback function that builds the condition
|
|
1382
|
+
* @returns The builder instance for method chaining
|
|
1383
|
+
*/
|
|
1384
|
+
condition(condition: Condition | ((op: ConditionOperator<T>) => Condition)): this;
|
|
1385
|
+
/**
|
|
1386
|
+
* Sets whether to return the item's previous values (if it existed).
|
|
1387
|
+
*
|
|
1388
|
+
* @options
|
|
1389
|
+
* - NONE: No return value
|
|
1390
|
+
* - ALL_OLD: Returns the item's previous state if it existed, no read capacity units are consumed
|
|
1391
|
+
* - CONSISTENT: Performs a GET operation after the put to retrieve the item's new state
|
|
1392
|
+
* - INPUT: Returns the input values that were passed to the operation
|
|
1393
|
+
*
|
|
1394
|
+
* @example
|
|
1395
|
+
* ```ts
|
|
1396
|
+
* // Get previous dinosaur state
|
|
1397
|
+
* const result = await builder
|
|
1398
|
+
* .returnValues('ALL_OLD')
|
|
1399
|
+
* .execute();
|
|
1400
|
+
*
|
|
1401
|
+
* if (result) {
|
|
1402
|
+
* console.log('Previous profile:', {
|
|
1403
|
+
* species: result.species,
|
|
1404
|
+
* status: result.status,
|
|
1405
|
+
* stats: {
|
|
1406
|
+
* health: result.stats.health,
|
|
1407
|
+
* threatLevel: result.stats.threatLevel
|
|
1408
|
+
* }
|
|
1409
|
+
* });
|
|
1410
|
+
* }
|
|
1411
|
+
*
|
|
1412
|
+
* // Return input values for create operations
|
|
1413
|
+
* const createResult = await builder
|
|
1414
|
+
* .returnValues('INPUT')
|
|
1415
|
+
* .execute();
|
|
1416
|
+
* ```
|
|
1417
|
+
*
|
|
1418
|
+
* @param returnValues - Use 'ALL_OLD' to return previous values, 'INPUT' to return input values, 'CONSISTENT' for fresh data, or 'NONE' (default).
|
|
1419
|
+
* @returns The builder instance for method chaining
|
|
1420
|
+
*/
|
|
1421
|
+
returnValues(returnValues: "ALL_OLD" | "NONE" | "CONSISTENT" | "INPUT"): this;
|
|
1422
|
+
/**
|
|
1423
|
+
* Generate the DynamoDB command parameters
|
|
1424
|
+
*/
|
|
1425
|
+
private toDynamoCommand;
|
|
1426
|
+
/**
|
|
1427
|
+
* Adds this put operation to a transaction.
|
|
1428
|
+
*
|
|
1429
|
+
* @example
|
|
1430
|
+
* ```ts
|
|
1431
|
+
* const transaction = new TransactionBuilder();
|
|
1432
|
+
*
|
|
1433
|
+
* // Add dinosaur to new habitat
|
|
1434
|
+
* new PutBuilder(executor, {
|
|
1435
|
+
* id: 'TREX-002',
|
|
1436
|
+
* location: 'PADDOCK-B',
|
|
1437
|
+
* status: 'ACTIVE',
|
|
1438
|
+
* transferDate: new Date().toISOString()
|
|
1439
|
+
* }, 'dinosaurs')
|
|
1440
|
+
* .withTransaction(transaction);
|
|
1441
|
+
*
|
|
1442
|
+
* // Update habitat records
|
|
1443
|
+
* new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-B' })
|
|
1444
|
+
* .add('occupants', 1)
|
|
1445
|
+
* .set('lastTransfer', new Date().toISOString())
|
|
1446
|
+
* .withTransaction(transaction);
|
|
1447
|
+
*
|
|
1448
|
+
* // Execute transfer atomically
|
|
1449
|
+
* await transaction.execute();
|
|
1450
|
+
* ```
|
|
1451
|
+
*
|
|
1452
|
+
* @param transaction - The transaction builder to add this operation to
|
|
1453
|
+
* @returns The builder instance for method chaining
|
|
1454
|
+
*/
|
|
1455
|
+
withTransaction(transaction: TransactionBuilder): this;
|
|
1456
|
+
/**
|
|
1457
|
+
* Adds this put operation to a batch with optional entity type information.
|
|
1458
|
+
*
|
|
1459
|
+
* @example Basic Usage
|
|
1460
|
+
* ```ts
|
|
1461
|
+
* const batch = table.batchBuilder();
|
|
1462
|
+
*
|
|
1463
|
+
* // Add multiple dinosaurs to batch
|
|
1464
|
+
* dinosaurRepo.create(newDino1).withBatch(batch);
|
|
1465
|
+
* dinosaurRepo.create(newDino2).withBatch(batch);
|
|
1466
|
+
* dinosaurRepo.create(newDino3).withBatch(batch);
|
|
1467
|
+
*
|
|
1468
|
+
* // Execute all operations efficiently
|
|
1469
|
+
* await batch.execute();
|
|
1470
|
+
* ```
|
|
1471
|
+
*
|
|
1472
|
+
* @example Typed Usage
|
|
1473
|
+
* ```ts
|
|
1474
|
+
* const batch = table.batchBuilder<{
|
|
1475
|
+
* User: UserEntity;
|
|
1476
|
+
* Order: OrderEntity;
|
|
1477
|
+
* }>();
|
|
1478
|
+
*
|
|
1479
|
+
* // Add operations with type information
|
|
1480
|
+
* userRepo.create(newUser).withBatch(batch, 'User');
|
|
1481
|
+
* orderRepo.create(newOrder).withBatch(batch, 'Order');
|
|
1482
|
+
*
|
|
1483
|
+
* // Execute and get typed results
|
|
1484
|
+
* const result = await batch.execute();
|
|
1485
|
+
* const users: UserEntity[] = result.reads.itemsByType.User;
|
|
1486
|
+
* ```
|
|
1487
|
+
*
|
|
1488
|
+
* @param batch - The batch builder to add this operation to
|
|
1489
|
+
* @param entityType - Optional entity type key for type tracking
|
|
1490
|
+
*/
|
|
1491
|
+
withBatch<TEntities extends Record<string, DynamoItem> = Record<string, DynamoItem>, K extends keyof TEntities = keyof TEntities>(batch: BatchBuilder<TEntities>, entityType?: K): void;
|
|
1492
|
+
/**
|
|
1493
|
+
* Executes the put operation against DynamoDB.
|
|
1494
|
+
*
|
|
1495
|
+
* @example
|
|
1496
|
+
* ```ts
|
|
1497
|
+
* try {
|
|
1498
|
+
* // Put with condition and return old values
|
|
1499
|
+
* const result = await new PutBuilder(executor, newItem, 'myTable')
|
|
1500
|
+
* .condition(op => op.eq('version', 1))
|
|
1501
|
+
* .returnValues('ALL_OLD')
|
|
1502
|
+
* .execute();
|
|
1503
|
+
*
|
|
1504
|
+
* console.log('Put successful, old item:', result);
|
|
1505
|
+
* } catch (error) {
|
|
1506
|
+
* // Handle condition check failure or other errors
|
|
1507
|
+
* console.error('Put failed:', error);
|
|
1508
|
+
* }
|
|
1509
|
+
* ```
|
|
1510
|
+
*
|
|
1511
|
+
* @returns A promise that resolves to the operation result (type depends on returnValues setting)
|
|
1512
|
+
* @throws Will throw an error if the condition check fails or other DynamoDB errors occur
|
|
1513
|
+
*/
|
|
1514
|
+
execute(): Promise<T | undefined>;
|
|
1515
|
+
/**
|
|
1516
|
+
* Gets a human-readable representation of the put command
|
|
1517
|
+
* with all expression placeholders replaced by their actual values.
|
|
1518
|
+
*
|
|
1519
|
+
* @example
|
|
1520
|
+
* ```ts
|
|
1521
|
+
* const debugInfo = new PutBuilder(executor, {
|
|
1522
|
+
* id: 'RAPTOR-003',
|
|
1523
|
+
* species: 'Velociraptor',
|
|
1524
|
+
* status: 'QUARANTINE',
|
|
1525
|
+
* stats: {
|
|
1526
|
+
* health: 100,
|
|
1527
|
+
* aggressionLevel: 7,
|
|
1528
|
+
* age: 2
|
|
1529
|
+
* }
|
|
1530
|
+
* }, 'dinosaurs')
|
|
1531
|
+
* .condition(op =>
|
|
1532
|
+
* op.and([
|
|
1533
|
+
* op.attributeNotExists('id'),
|
|
1534
|
+
* op.eq('quarantineStatus', 'READY'),
|
|
1535
|
+
* op.gt('securityLevel', 8)
|
|
1536
|
+
* ])
|
|
1537
|
+
* )
|
|
1538
|
+
* .debug();
|
|
1539
|
+
*
|
|
1540
|
+
* console.log('Dinosaur transfer command:', debugInfo);
|
|
1541
|
+
* ```
|
|
1542
|
+
*
|
|
1543
|
+
* @returns A readable representation of the put command with resolved expressions
|
|
1544
|
+
*/
|
|
1545
|
+
debug(): {
|
|
1546
|
+
raw: PutCommandParams;
|
|
1547
|
+
readable: {
|
|
1548
|
+
conditionExpression?: string;
|
|
1549
|
+
updateExpression?: string;
|
|
1550
|
+
filterExpression?: string;
|
|
1551
|
+
keyConditionExpression?: string;
|
|
1552
|
+
projectionExpression?: string;
|
|
1553
|
+
};
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/**
|
|
1558
|
+
* A utility class for handling DynamoDB pagination.
|
|
1559
|
+
* Use this class when you need to:
|
|
1560
|
+
* - Browse large collections of dinosaurs
|
|
1561
|
+
* - Review extensive security logs
|
|
1562
|
+
* - Analyze habitat inspection history
|
|
1563
|
+
* - Process feeding schedules
|
|
1564
|
+
*
|
|
1565
|
+
* The paginator maintains internal state and automatically handles:
|
|
1566
|
+
* - Page boundaries
|
|
1567
|
+
* - Result set limits
|
|
1568
|
+
* - Continuation tokens
|
|
1569
|
+
*
|
|
1570
|
+
* @example
|
|
1571
|
+
* ```typescript
|
|
1572
|
+
* // List all velociraptors with pagination
|
|
1573
|
+
* const paginator = new QueryBuilder(executor, eq('species', 'Velociraptor'))
|
|
1574
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1575
|
+
* .paginate(10);
|
|
1576
|
+
*
|
|
1577
|
+
* // Process each page of dinosaurs
|
|
1578
|
+
* while (paginator.hasNextPage()) {
|
|
1579
|
+
* const page = await paginator.getNextPage();
|
|
1580
|
+
* console.log(`Processing page ${page.page} of velociraptors`);
|
|
1581
|
+
*
|
|
1582
|
+
* for (const raptor of page.items) {
|
|
1583
|
+
* console.log(`- ${raptor.id}: Health=${raptor.stats.health}`);
|
|
1584
|
+
* }
|
|
1585
|
+
* }
|
|
1586
|
+
* ```
|
|
1587
|
+
*
|
|
1588
|
+
* @typeParam T - The type of items being paginated
|
|
1589
|
+
* @typeParam TConfig - The table configuration type
|
|
1590
|
+
*/
|
|
1591
|
+
declare class Paginator<T extends DynamoItem, TConfig extends TableConfig = TableConfig> {
|
|
1592
|
+
private queryBuilder;
|
|
1593
|
+
private readonly pageSize?;
|
|
1594
|
+
private currentPage;
|
|
1595
|
+
private lastEvaluatedKey?;
|
|
1596
|
+
private hasMorePages;
|
|
1597
|
+
private totalItemsRetrieved;
|
|
1598
|
+
private readonly overallLimit?;
|
|
1599
|
+
constructor(queryBuilder: QueryBuilderInterface<T, TConfig>, pageSize?: number);
|
|
1600
|
+
/**
|
|
1601
|
+
* Gets the current page number (1-indexed).
|
|
1602
|
+
*
|
|
1603
|
+
* @example
|
|
1604
|
+
* ```ts
|
|
1605
|
+
* const paginator = new QueryBuilder(executor, eq('species', 'Tyrannosaurus'))
|
|
1606
|
+
* .paginate(5);
|
|
1607
|
+
*
|
|
1608
|
+
* await paginator.getNextPage();
|
|
1609
|
+
* console.log(`Reviewing T-Rex group ${paginator.getCurrentPage()}`);
|
|
1610
|
+
* ```
|
|
1611
|
+
*
|
|
1612
|
+
* @returns The current page number, starting from 1
|
|
1613
|
+
*/
|
|
1614
|
+
getCurrentPage(): number;
|
|
1615
|
+
/**
|
|
1616
|
+
* Checks if there are more pages of dinosaurs or habitats to process.
|
|
1617
|
+
*
|
|
1618
|
+
* This method takes into account both:
|
|
1619
|
+
* - DynamoDB's lastEvaluatedKey mechanism
|
|
1620
|
+
* - Any overall limit set on the query
|
|
1621
|
+
*
|
|
1622
|
+
* @example
|
|
1623
|
+
* ```ts
|
|
1624
|
+
* // Process all security incidents
|
|
1625
|
+
* const paginator = new QueryBuilder(executor, eq('type', 'SECURITY_BREACH'))
|
|
1626
|
+
* .sortDescending()
|
|
1627
|
+
* .paginate(10);
|
|
1628
|
+
*
|
|
1629
|
+
* while (paginator.hasNextPage()) {
|
|
1630
|
+
* const page = await paginator.getNextPage();
|
|
1631
|
+
* for (const incident of page.items) {
|
|
1632
|
+
* await processSecurityBreach(incident);
|
|
1633
|
+
* }
|
|
1634
|
+
* console.log(`Processed incidents page ${page.page}`);
|
|
1635
|
+
* }
|
|
1636
|
+
* ```
|
|
1637
|
+
*
|
|
1638
|
+
* @returns true if there are more pages available, false otherwise
|
|
1639
|
+
*/
|
|
1640
|
+
hasNextPage(): boolean;
|
|
1641
|
+
/**
|
|
1642
|
+
* Retrieves the next page of dinosaurs or habitats from DynamoDB.
|
|
1643
|
+
*
|
|
1644
|
+
* This method handles:
|
|
1645
|
+
* - Automatic continuation between groups
|
|
1646
|
+
* - Respect for park capacity limits
|
|
1647
|
+
* - Group size adjustments for safety
|
|
1648
|
+
*
|
|
1649
|
+
* @example
|
|
1650
|
+
* ```ts
|
|
1651
|
+
* const paginator = new QueryBuilder(executor, eq('species', 'Velociraptor'))
|
|
1652
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1653
|
+
* .paginate(5);
|
|
1654
|
+
*
|
|
1655
|
+
* // Check first raptor group
|
|
1656
|
+
* const page1 = await paginator.getNextPage();
|
|
1657
|
+
* console.log(`Found ${page1.items.length} active raptors`);
|
|
1658
|
+
*
|
|
1659
|
+
* // Continue inspection if more groups exist
|
|
1660
|
+
* if (page1.hasNextPage) {
|
|
1661
|
+
* const page2 = await paginator.getNextPage();
|
|
1662
|
+
* console.log(`Inspecting raptor group ${page2.page}`);
|
|
1663
|
+
*
|
|
1664
|
+
* for (const raptor of page2.items) {
|
|
1665
|
+
* await performHealthCheck(raptor);
|
|
1666
|
+
* }
|
|
1667
|
+
* }
|
|
1668
|
+
* ```
|
|
1669
|
+
*
|
|
1670
|
+
* @returns A promise that resolves to a PaginationResult containing:
|
|
1671
|
+
* - items: The dinosaurs/habitats for this page
|
|
1672
|
+
* - hasNextPage: Whether more groups exist
|
|
1673
|
+
* - page: The current group number
|
|
1674
|
+
* - lastEvaluatedKey: DynamoDB's continuation token
|
|
1675
|
+
*/
|
|
1676
|
+
getNextPage(): Promise<PaginationResult<T>>;
|
|
1677
|
+
/**
|
|
1678
|
+
* Gets all remaining dinosaurs or habitats and combines them into a single array.
|
|
1679
|
+
*
|
|
1680
|
+
* @example
|
|
1681
|
+
* ```ts
|
|
1682
|
+
* // Get complete carnivore inventory
|
|
1683
|
+
* const paginator = new QueryBuilder(executor, eq('diet', 'CARNIVORE'))
|
|
1684
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1685
|
+
* .paginate(10);
|
|
1686
|
+
*
|
|
1687
|
+
* try {
|
|
1688
|
+
* const allCarnivores = await paginator.getAllPages();
|
|
1689
|
+
* console.log(`Park contains ${allCarnivores.length} active carnivores`);
|
|
1690
|
+
*
|
|
1691
|
+
* // Calculate total threat level
|
|
1692
|
+
* const totalThreat = allCarnivores.reduce(
|
|
1693
|
+
* (sum, dino) => sum + dino.stats.threatLevel,
|
|
1694
|
+
* 0
|
|
1695
|
+
* );
|
|
1696
|
+
* console.log(`Total threat level: ${totalThreat}`);
|
|
1697
|
+
* } catch (error) {
|
|
1698
|
+
* console.error('Failed to complete carnivore census:', error);
|
|
1699
|
+
* }
|
|
1700
|
+
* ```
|
|
1701
|
+
*
|
|
1702
|
+
* @returns A promise that resolves to an array containing all remaining items
|
|
1703
|
+
*/
|
|
1704
|
+
getAllPages(): Promise<T[]>;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
/**
|
|
1708
|
+
* Configuration options for DynamoDB filter operations.
|
|
1709
|
+
* These are common options shared between query and scan operations.
|
|
1710
|
+
*/
|
|
1711
|
+
interface FilterOptions {
|
|
1712
|
+
/** Filter conditions applied to results */
|
|
1713
|
+
filter?: Condition;
|
|
1714
|
+
/** Maximum number of items to return */
|
|
1715
|
+
limit?: number;
|
|
1716
|
+
/** Name of the Global Secondary Index to use */
|
|
1717
|
+
indexName?: string;
|
|
1718
|
+
/** Whether to use strongly consistent reads */
|
|
1719
|
+
consistentRead?: boolean;
|
|
1720
|
+
/** List of attributes to return in the result */
|
|
1721
|
+
projection?: string[];
|
|
1722
|
+
/** Token for starting the operation from a specific point */
|
|
1723
|
+
lastEvaluatedKey?: DynamoItem;
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* Abstract base builder for creating DynamoDB filter operations.
|
|
1727
|
+
* This class provides common functionality for both Query and Scan operations.
|
|
1728
|
+
*
|
|
1729
|
+
* The builder supports:
|
|
1730
|
+
* - Type-safe GSI selection
|
|
1731
|
+
* - Complex filter conditions
|
|
1732
|
+
* - Pagination
|
|
1733
|
+
* - Consistent reads
|
|
1734
|
+
* - Attribute projection
|
|
1735
|
+
*
|
|
1736
|
+
* @typeParam T - The type of items being filtered
|
|
1737
|
+
* @typeParam TConfig - The table configuration type for type-safe GSI selection
|
|
1738
|
+
*/
|
|
1739
|
+
declare abstract class FilterBuilder<T extends DynamoItem, TConfig extends TableConfig = TableConfig> implements FilterBuilderInterface<T, TConfig> {
|
|
1740
|
+
protected options: FilterOptions;
|
|
1741
|
+
protected selectedFields: Set<string>;
|
|
1742
|
+
/**
|
|
1743
|
+
* Sets the maximum number of items to return.
|
|
1744
|
+
*
|
|
1745
|
+
* Note: This limit applies to the items that match the key condition
|
|
1746
|
+
* before any filter expressions are applied.
|
|
1747
|
+
*
|
|
1748
|
+
* @example
|
|
1749
|
+
* ```typescript
|
|
1750
|
+
* // Get first 10 dinosaurs
|
|
1751
|
+
* const result = await builder
|
|
1752
|
+
* .limit(10)
|
|
1753
|
+
* .execute();
|
|
1754
|
+
* ```
|
|
1755
|
+
*
|
|
1756
|
+
* @param limit - Maximum number of items to return
|
|
1757
|
+
* @returns The builder instance for method chaining
|
|
1758
|
+
*/
|
|
1759
|
+
limit(limit: number): this;
|
|
1760
|
+
/**
|
|
1761
|
+
* Gets the current limit set on the operation.
|
|
1762
|
+
* This is used internally by the paginator to manage result sets.
|
|
1763
|
+
*
|
|
1764
|
+
* @returns The current limit or undefined if no limit is set
|
|
1765
|
+
*/
|
|
1766
|
+
getLimit(): number | undefined;
|
|
1767
|
+
/**
|
|
1768
|
+
* Specifies a Global Secondary Index (GSI) to use for the operation.
|
|
1769
|
+
*
|
|
1770
|
+
* @example
|
|
1771
|
+
* ```typescript
|
|
1772
|
+
* // Find all dinosaurs of a specific species
|
|
1773
|
+
* builder
|
|
1774
|
+
* .useIndex('species-status-index')
|
|
1775
|
+
* .filter(op => op.eq('status', 'ACTIVE'));
|
|
1776
|
+
*
|
|
1777
|
+
* // Search high-security habitats
|
|
1778
|
+
* builder
|
|
1779
|
+
* .useIndex('security-level-index')
|
|
1780
|
+
* .filter(op =>
|
|
1781
|
+
* op.and([
|
|
1782
|
+
* op.gt('securityLevel', 8),
|
|
1783
|
+
* op.eq('status', 'OPERATIONAL')
|
|
1784
|
+
* ])
|
|
1785
|
+
* );
|
|
1786
|
+
* ```
|
|
1787
|
+
*
|
|
1788
|
+
* @param indexName - The name of the GSI to use (type-safe based on table configuration)
|
|
1789
|
+
* @returns The builder instance for method chaining
|
|
1790
|
+
*/
|
|
1791
|
+
useIndex<I extends GSINames<TConfig>>(indexName: I): this;
|
|
1792
|
+
/**
|
|
1793
|
+
* Sets whether to use strongly consistent reads for the operation.
|
|
1794
|
+
*
|
|
1795
|
+
* Note:
|
|
1796
|
+
* - Consistent reads are not available on GSIs
|
|
1797
|
+
* - Consistent reads consume twice the throughput
|
|
1798
|
+
* - Default is eventually consistent reads
|
|
1799
|
+
*
|
|
1800
|
+
* @example
|
|
1801
|
+
* ```typescript
|
|
1802
|
+
* // Check immediate dinosaur status
|
|
1803
|
+
* const result = await builder
|
|
1804
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1805
|
+
* .consistentRead()
|
|
1806
|
+
* .execute();
|
|
1807
|
+
*
|
|
1808
|
+
* // Monitor security breaches
|
|
1809
|
+
* const result = await builder
|
|
1810
|
+
* .useIndex('primary-index')
|
|
1811
|
+
* .consistentRead(isEmergencyMode)
|
|
1812
|
+
* .execute();
|
|
1813
|
+
* ```
|
|
1814
|
+
*
|
|
1815
|
+
* @param consistentRead - Whether to use consistent reads (defaults to true)
|
|
1816
|
+
* @returns The builder instance for method chaining
|
|
1817
|
+
*/
|
|
1818
|
+
consistentRead(consistentRead?: boolean): this;
|
|
1819
|
+
/**
|
|
1820
|
+
* Adds a filter expression to refine the operation results.
|
|
1821
|
+
*
|
|
1822
|
+
* @example
|
|
1823
|
+
* ```typescript
|
|
1824
|
+
* // Find aggressive carnivores
|
|
1825
|
+
* builder.filter(op =>
|
|
1826
|
+
* op.and([
|
|
1827
|
+
* op.eq('diet', 'CARNIVORE'),
|
|
1828
|
+
* op.gt('aggressionLevel', 7),
|
|
1829
|
+
* op.eq('status', 'ACTIVE')
|
|
1830
|
+
* ])
|
|
1831
|
+
* );
|
|
1832
|
+
*
|
|
1833
|
+
* // Search suitable breeding habitats
|
|
1834
|
+
* builder.filter(op =>
|
|
1835
|
+
* op.and([
|
|
1836
|
+
* op.between('temperature', 25, 30),
|
|
1837
|
+
* op.lt('currentOccupants', 3),
|
|
1838
|
+
* op.eq('quarantineStatus', 'CLEAR')
|
|
1839
|
+
* ])
|
|
1840
|
+
* );
|
|
1841
|
+
* ```
|
|
1842
|
+
*
|
|
1843
|
+
* @param condition - Either a Condition object or a callback function that builds the condition
|
|
1844
|
+
* @returns The builder instance for method chaining
|
|
1845
|
+
*/
|
|
1846
|
+
filter(condition: Condition | ((op: ConditionOperator<T>) => Condition)): this;
|
|
1847
|
+
private getConditionOperator;
|
|
1848
|
+
/**
|
|
1849
|
+
* Specifies which attributes to return in the results.
|
|
1850
|
+
*
|
|
1851
|
+
* @example
|
|
1852
|
+
* ```typescript
|
|
1853
|
+
* // Get basic dinosaur info
|
|
1854
|
+
* builder.select([
|
|
1855
|
+
* 'species',
|
|
1856
|
+
* 'status',
|
|
1857
|
+
* 'stats.health',
|
|
1858
|
+
* 'stats.aggressionLevel'
|
|
1859
|
+
* ]);
|
|
1860
|
+
*
|
|
1861
|
+
* // Monitor habitat conditions
|
|
1862
|
+
* builder
|
|
1863
|
+
* .select('securityStatus')
|
|
1864
|
+
* .select([
|
|
1865
|
+
* 'currentOccupants',
|
|
1866
|
+
* 'temperature',
|
|
1867
|
+
* 'lastInspectionDate'
|
|
1868
|
+
* ]);
|
|
1869
|
+
* ```
|
|
1870
|
+
*
|
|
1871
|
+
* @param fields - A single field name or an array of field names to return
|
|
1872
|
+
* @returns The builder instance for method chaining
|
|
1873
|
+
*/
|
|
1874
|
+
select<K extends Path<T>>(fields: K | K[]): this;
|
|
1875
|
+
/**
|
|
1876
|
+
* Creates a paginator that handles DynamoDB pagination automatically.
|
|
1877
|
+
* The paginator handles:
|
|
1878
|
+
* - Tracking the last evaluated key
|
|
1879
|
+
* - Managing page boundaries
|
|
1880
|
+
* - Respecting overall query limits
|
|
1881
|
+
*
|
|
1882
|
+
* @example
|
|
1883
|
+
* ```typescript
|
|
1884
|
+
* // Create a paginator for dinosaur records with specific page size
|
|
1885
|
+
* const paginator = builder
|
|
1886
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1887
|
+
* .paginate(10);
|
|
1888
|
+
*
|
|
1889
|
+
* // Create a paginator with automatic DynamoDB paging (no page size limit)
|
|
1890
|
+
* const autoPaginator = builder
|
|
1891
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1892
|
+
* .paginate();
|
|
1893
|
+
*
|
|
1894
|
+
* // Process pages of dinosaur results
|
|
1895
|
+
* while (paginator.hasNextPage()) {
|
|
1896
|
+
* const page = await paginator.getNextPage();
|
|
1897
|
+
* console.log(`Processing page ${page.page}, count: ${page.items.length}`);
|
|
1898
|
+
* // Process dinosaur data
|
|
1899
|
+
* }
|
|
1900
|
+
* ```
|
|
1901
|
+
*
|
|
1902
|
+
* @param pageSize - The number of items to return per page. If not provided, DynamoDB will automatically determine page sizes.
|
|
1903
|
+
* @returns A Paginator instance that manages the pagination state
|
|
1904
|
+
* @see Paginator for more pagination control options
|
|
1905
|
+
*/
|
|
1906
|
+
paginate(pageSize?: number): Paginator<T, TConfig>;
|
|
1907
|
+
/**
|
|
1908
|
+
* Sets the starting point using a previous lastEvaluatedKey.
|
|
1909
|
+
*
|
|
1910
|
+
* Note: This method is typically used for manual pagination.
|
|
1911
|
+
* For automatic pagination, use the paginate() method instead.
|
|
1912
|
+
*
|
|
1913
|
+
* @example
|
|
1914
|
+
* ```typescript
|
|
1915
|
+
* // First batch of dinosaurs
|
|
1916
|
+
* const result1 = await builder
|
|
1917
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1918
|
+
* .limit(5)
|
|
1919
|
+
* .execute();
|
|
1920
|
+
*
|
|
1921
|
+
* const lastKey = result1.getLastEvaluatedKey();
|
|
1922
|
+
* if (lastKey) {
|
|
1923
|
+
* // Continue listing dinosaurs
|
|
1924
|
+
* const result2 = await builder
|
|
1925
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
1926
|
+
* .startFrom(lastKey)
|
|
1927
|
+
* .limit(5)
|
|
1928
|
+
* .execute();
|
|
1929
|
+
*
|
|
1930
|
+
* const items = await result2.toArray();
|
|
1931
|
+
* console.log('Additional dinosaurs:', items);
|
|
1932
|
+
* }
|
|
1933
|
+
* ```
|
|
1934
|
+
*
|
|
1935
|
+
* @param lastEvaluatedKey - The exclusive start key from a previous result
|
|
1936
|
+
* @returns The builder instance for method chaining
|
|
1937
|
+
*/
|
|
1938
|
+
startFrom(lastEvaluatedKey: DynamoItem): this;
|
|
1939
|
+
/**
|
|
1940
|
+
* Creates a deep clone of this builder instance.
|
|
1941
|
+
*
|
|
1942
|
+
* This is particularly useful when:
|
|
1943
|
+
* - Implementing pagination (used internally by paginate())
|
|
1944
|
+
* - Creating operation templates
|
|
1945
|
+
* - Running multiple variations of an operation
|
|
1946
|
+
*
|
|
1947
|
+
* @example
|
|
1948
|
+
* ```typescript
|
|
1949
|
+
* // Create base dinosaur query
|
|
1950
|
+
* const baseBuilder = builder
|
|
1951
|
+
* .useIndex('status-index')
|
|
1952
|
+
* .select(['id', 'status', 'location']);
|
|
1953
|
+
*
|
|
1954
|
+
* // Check active dinosaurs
|
|
1955
|
+
* const activeRaptors = baseBuilder.clone()
|
|
1956
|
+
* .filter(op => op.eq('status', 'HUNTING'))
|
|
1957
|
+
* .execute();
|
|
1958
|
+
*
|
|
1959
|
+
* // Check contained dinosaurs
|
|
1960
|
+
* const containedRaptors = baseBuilder.clone()
|
|
1961
|
+
* .filter(op => op.eq('status', 'CONTAINED'))
|
|
1962
|
+
* .execute();
|
|
1963
|
+
* ```
|
|
1964
|
+
*
|
|
1965
|
+
* @returns A new builder instance with the same configuration
|
|
1966
|
+
*/
|
|
1967
|
+
abstract clone(): FilterBuilderInterface<T, TConfig>;
|
|
1968
|
+
/**
|
|
1969
|
+
* Executes the operation against DynamoDB and returns a generator that behaves like an array.
|
|
1970
|
+
* This method must be implemented by subclasses to handle
|
|
1971
|
+
* their specific execution logic.
|
|
1972
|
+
*/
|
|
1973
|
+
abstract execute(): Promise<ResultIterator<T, TConfig>>;
|
|
1974
|
+
}
|
|
1975
|
+
|
|
1976
|
+
/**
|
|
1977
|
+
* Configuration options for DynamoDB query operations.
|
|
1978
|
+
* Extends the base FilterOptions with query-specific options.
|
|
1979
|
+
*/
|
|
1980
|
+
interface QueryOptions extends FilterOptions {
|
|
1981
|
+
/** Condition for the sort key in the table or index */
|
|
1982
|
+
sortKeyCondition?: Condition;
|
|
1983
|
+
/** Direction of sort key traversal (true for ascending, false for descending) */
|
|
1984
|
+
scanIndexForward?: boolean;
|
|
1985
|
+
}
|
|
1986
|
+
/**
|
|
1987
|
+
* Function type for executing DynamoDB query operations.
|
|
1988
|
+
* @typeParam T - The type of items being queried
|
|
1989
|
+
*/
|
|
1990
|
+
type QueryExecutor<T extends DynamoItem> = (keyCondition: Condition, options: QueryOptions) => Promise<{
|
|
1991
|
+
items: T[];
|
|
1992
|
+
lastEvaluatedKey?: Record<string, unknown>;
|
|
1993
|
+
}>;
|
|
1994
|
+
/**
|
|
1995
|
+
* Builder for creating DynamoDB query operations.
|
|
1996
|
+
*
|
|
1997
|
+
* The builder supports:
|
|
1998
|
+
* - Type-safe GSI selection
|
|
1999
|
+
* - Complex filter conditions
|
|
2000
|
+
* - Automatic pagination handling
|
|
2001
|
+
* - Consistent reads
|
|
2002
|
+
* - Forward and reverse sorting
|
|
2003
|
+
*
|
|
2004
|
+
* @example
|
|
2005
|
+
* ```typescript
|
|
2006
|
+
* // Simple query
|
|
2007
|
+
* const result = await new QueryBuilder(executor, eq('userId', '123'))
|
|
2008
|
+
* .execute();
|
|
2009
|
+
*
|
|
2010
|
+
* // Complex query with GSI and filtering
|
|
2011
|
+
* const result = await new QueryBuilder(executor, eq('status', 'ACTIVE'))
|
|
2012
|
+
* .useIndex('status-index')
|
|
2013
|
+
* .filter(op => op.beginsWith('name', 'John'))
|
|
2014
|
+
* .select(['id', 'name', 'email'])
|
|
2015
|
+
* .sortDescending()
|
|
2016
|
+
* .limit(10)
|
|
2017
|
+
* .execute();
|
|
2018
|
+
*
|
|
2019
|
+
* // Query with pagination
|
|
2020
|
+
* const paginator = new QueryBuilder(executor, eq('type', 'order'))
|
|
2021
|
+
* .paginate(25);
|
|
2022
|
+
*
|
|
2023
|
+
* while (paginator.hasNextPage()) {
|
|
2024
|
+
* const page = await paginator.getNextPage();
|
|
2025
|
+
* // Process page.items
|
|
2026
|
+
* }
|
|
2027
|
+
* ```
|
|
2028
|
+
*
|
|
2029
|
+
* @typeParam T - The type of items being queried
|
|
2030
|
+
* @typeParam TConfig - The table configuration type for type-safe GSI selection
|
|
2031
|
+
*/
|
|
2032
|
+
declare class QueryBuilder<T extends DynamoItem, TConfig extends TableConfig = TableConfig> extends FilterBuilder<T, TConfig> implements QueryBuilderInterface<T, TConfig> {
|
|
2033
|
+
private readonly keyCondition;
|
|
2034
|
+
protected options: QueryOptions;
|
|
2035
|
+
protected readonly executor: QueryExecutor<T>;
|
|
2036
|
+
constructor(executor: QueryExecutor<T>, keyCondition: Condition);
|
|
2037
|
+
/**
|
|
2038
|
+
* Sets the maximum number of items to return from the query.
|
|
2039
|
+
*
|
|
2040
|
+
* Note: This is the default behavior if no sort order is specified.
|
|
2041
|
+
*
|
|
2042
|
+
* @example
|
|
2043
|
+
* ```typescript
|
|
2044
|
+
* // Get orders in chronological order
|
|
2045
|
+
* const result = await new QueryBuilder(executor, eq('userId', '123'))
|
|
2046
|
+
* .sortAscending()
|
|
2047
|
+
* .execute();
|
|
2048
|
+
*
|
|
2049
|
+
* // Get events from oldest to newest
|
|
2050
|
+
* const result = await new QueryBuilder(executor, eq('entityId', 'order-123'))
|
|
2051
|
+
* .useIndex('entity-timestamp-index')
|
|
2052
|
+
* .sortAscending()
|
|
2053
|
+
* .execute();
|
|
2054
|
+
* ```
|
|
2055
|
+
*
|
|
2056
|
+
* @returns The builder instance for method chaining
|
|
2057
|
+
*/
|
|
2058
|
+
/**
|
|
2059
|
+
* Sets the query to return items in ascending order by sort key.
|
|
2060
|
+
*
|
|
2061
|
+
* @example
|
|
2062
|
+
* ```typescript
|
|
2063
|
+
* // List dinosaurs by age
|
|
2064
|
+
* const result = await new QueryBuilder(executor, eq('species', 'Velociraptor'))
|
|
2065
|
+
* .useIndex('age-index')
|
|
2066
|
+
* .sortAscending()
|
|
2067
|
+
* .execute();
|
|
2068
|
+
*
|
|
2069
|
+
* // View incidents chronologically
|
|
2070
|
+
* const result = await new QueryBuilder(executor, eq('type', 'SECURITY_BREACH'))
|
|
2071
|
+
* .useIndex('date-index')
|
|
2072
|
+
* .sortAscending()
|
|
2073
|
+
* .execute();
|
|
2074
|
+
* ```
|
|
2075
|
+
*
|
|
2076
|
+
* @returns The builder instance for method chaining
|
|
2077
|
+
*/
|
|
2078
|
+
sortAscending(): this;
|
|
2079
|
+
/**
|
|
2080
|
+
* Sets the query to return items in descending order by sort key.
|
|
2081
|
+
*
|
|
2082
|
+
* @example
|
|
2083
|
+
* ```typescript
|
|
2084
|
+
* // Get most recent security incidents
|
|
2085
|
+
* const result = await new QueryBuilder(executor, eq('type', 'SECURITY_BREACH'))
|
|
2086
|
+
* .useIndex('date-index')
|
|
2087
|
+
* .sortDescending()
|
|
2088
|
+
* .limit(10)
|
|
2089
|
+
* .execute();
|
|
2090
|
+
*
|
|
2091
|
+
* // Check latest dinosaur activities
|
|
2092
|
+
* const result = await new QueryBuilder(executor, eq('species', 'Velociraptor'))
|
|
2093
|
+
* .useIndex('activity-time-index')
|
|
2094
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
2095
|
+
* .sortDescending()
|
|
2096
|
+
* .execute();
|
|
2097
|
+
* ```
|
|
2098
|
+
*
|
|
2099
|
+
* @returns The builder instance for method chaining
|
|
2100
|
+
*/
|
|
2101
|
+
sortDescending(): this;
|
|
2102
|
+
/**
|
|
2103
|
+
* Creates a deep clone of this QueryBuilder instance.
|
|
2104
|
+
*
|
|
2105
|
+
* This is particularly useful when:
|
|
2106
|
+
* - Implementing pagination (used internally by paginate())
|
|
2107
|
+
* - Creating query templates
|
|
2108
|
+
* - Running multiple variations of a query
|
|
2109
|
+
*
|
|
2110
|
+
* @example
|
|
2111
|
+
* ```typescript
|
|
2112
|
+
* // Create base dinosaur query
|
|
2113
|
+
* const baseQuery = new QueryBuilder(executor, eq('species', 'Velociraptor'))
|
|
2114
|
+
* .useIndex('status-index')
|
|
2115
|
+
* .select(['id', 'status', 'location']);
|
|
2116
|
+
*
|
|
2117
|
+
* // Check active dinosaurs
|
|
2118
|
+
* const activeRaptors = baseQuery.clone()
|
|
2119
|
+
* .filter(op => op.eq('status', 'HUNTING'))
|
|
2120
|
+
* .execute();
|
|
2121
|
+
*
|
|
2122
|
+
* // Check contained dinosaurs
|
|
2123
|
+
* const containedRaptors = baseQuery.clone()
|
|
2124
|
+
* .filter(op => op.eq('status', 'CONTAINED'))
|
|
2125
|
+
* .execute();
|
|
2126
|
+
*
|
|
2127
|
+
* // Check sedated dinosaurs
|
|
2128
|
+
* const sedatedRaptors = baseQuery.clone()
|
|
2129
|
+
* .filter(op => op.eq('status', 'SEDATED'))
|
|
2130
|
+
* .execute();
|
|
2131
|
+
* ```
|
|
2132
|
+
*
|
|
2133
|
+
* @returns A new QueryBuilder instance with the same configuration
|
|
2134
|
+
*/
|
|
2135
|
+
clone(): QueryBuilder<T, TConfig>;
|
|
2136
|
+
private deepCloneFilter;
|
|
2137
|
+
/**
|
|
2138
|
+
* Executes the query against DynamoDB and returns a generator that behaves like an array.
|
|
2139
|
+
*
|
|
2140
|
+
* The generator automatically handles pagination and provides array-like methods
|
|
2141
|
+
* for processing results efficiently without loading everything into memory at once.
|
|
2142
|
+
*
|
|
2143
|
+
* @example
|
|
2144
|
+
* ```typescript
|
|
2145
|
+
* try {
|
|
2146
|
+
* // Find active carnivores with automatic pagination
|
|
2147
|
+
* const results = await new QueryBuilder(executor, eq('habitatId', 'PADDOCK-A'))
|
|
2148
|
+
* .useIndex('species-status-index')
|
|
2149
|
+
* .filter(op =>
|
|
2150
|
+
* op.and([
|
|
2151
|
+
* op.eq('diet', 'CARNIVORE'),
|
|
2152
|
+
* op.eq('status', 'ACTIVE'),
|
|
2153
|
+
* op.gt('aggressionLevel', 7)
|
|
2154
|
+
* ])
|
|
2155
|
+
* )
|
|
2156
|
+
* .sortDescending()
|
|
2157
|
+
* .execute();
|
|
2158
|
+
*
|
|
2159
|
+
* // Use like an array with automatic pagination
|
|
2160
|
+
* for await (const dinosaur of results) {
|
|
2161
|
+
* console.log(`Processing ${dinosaur.name}`);
|
|
2162
|
+
* }
|
|
2163
|
+
*
|
|
2164
|
+
* // Or convert to array and use array methods
|
|
2165
|
+
* const allItems = await results.toArray();
|
|
2166
|
+
* const dangerousOnes = allItems.filter(dino => dino.aggressionLevel > 9);
|
|
2167
|
+
* const totalCount = allItems.length;
|
|
2168
|
+
* } catch (error) {
|
|
2169
|
+
* console.error('Security scan failed:', error);
|
|
2170
|
+
* }
|
|
2171
|
+
* ```
|
|
2172
|
+
*
|
|
2173
|
+
* @returns A promise that resolves to a ResultGenerator that behaves like an array
|
|
2174
|
+
*/
|
|
2175
|
+
execute(): Promise<ResultIterator<T, TConfig>>;
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
/**
|
|
2179
|
+
* Configuration options for DynamoDB update operations.
|
|
2180
|
+
*/
|
|
2181
|
+
interface UpdateOptions {
|
|
2182
|
+
/** Optional condition that must be satisfied for the update to succeed */
|
|
2183
|
+
condition?: Condition;
|
|
2184
|
+
/** Determines which item attributes to include in the response */
|
|
2185
|
+
returnValues?: "ALL_NEW" | "UPDATED_NEW" | "ALL_OLD" | "UPDATED_OLD" | "NONE";
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Function type for executing DynamoDB update operations.
|
|
2189
|
+
* @typeParam T - The type of the item being updated
|
|
2190
|
+
*/
|
|
2191
|
+
type UpdateExecutor<T extends DynamoItem> = (params: UpdateCommandParams) => Promise<{
|
|
2192
|
+
item?: T;
|
|
2193
|
+
}>;
|
|
2194
|
+
/**
|
|
2195
|
+
* Represents a single update action within an update operation.
|
|
2196
|
+
* Each action modifies the item in a specific way:
|
|
2197
|
+
* - SET: Modify or add attributes
|
|
2198
|
+
* - REMOVE: Delete attributes
|
|
2199
|
+
* - ADD: Update numbers and sets
|
|
2200
|
+
* - DELETE: Remove elements from a set
|
|
2201
|
+
*/
|
|
2202
|
+
type UpdateAction = {
|
|
2203
|
+
/** The type of update action */
|
|
2204
|
+
type: "SET" | "REMOVE" | "ADD" | "DELETE";
|
|
2205
|
+
/** The attribute path to update */
|
|
2206
|
+
path: string;
|
|
2207
|
+
/** The value to use in the update (not used for REMOVE actions) */
|
|
2208
|
+
value?: unknown;
|
|
2209
|
+
};
|
|
2210
|
+
/**
|
|
2211
|
+
* Type utility to get the element type of a set.
|
|
2212
|
+
* Extracts the element type from either a Set or Array type.
|
|
2213
|
+
* @typeParam T - The set or array type
|
|
2214
|
+
*/
|
|
2215
|
+
type SetElementType<T> = T extends Set<infer U> ? U : T extends Array<infer U> ? U : never;
|
|
2216
|
+
/**
|
|
2217
|
+
* Type utility to get the element type from a path that points to a set.
|
|
2218
|
+
* Combines PathType and SetElementType to get the element type at a specific path.
|
|
2219
|
+
* @typeParam T - The type of the item
|
|
2220
|
+
* @typeParam K - The path within the item
|
|
2221
|
+
*/
|
|
2222
|
+
type PathSetElementType<T, K extends Path<T>> = SetElementType<PathType<T, K>>;
|
|
2223
|
+
/**
|
|
2224
|
+
* Builder for creating DynamoDB update operations.
|
|
2225
|
+
*
|
|
2226
|
+
* The builder supports all DynamoDB update operations:
|
|
2227
|
+
* - SET: Modify or add attributes
|
|
2228
|
+
* - REMOVE: Delete attributes
|
|
2229
|
+
* - ADD: Update numbers and sets
|
|
2230
|
+
* - DELETE: Remove elements from a set
|
|
2231
|
+
*
|
|
2232
|
+
* @example
|
|
2233
|
+
* ```typescript
|
|
2234
|
+
* // Simple update
|
|
2235
|
+
* const result = await new UpdateBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
|
|
2236
|
+
* .set('status', 'HUNTING')
|
|
2237
|
+
* .set('lastFed', new Date().toISOString())
|
|
2238
|
+
* .execute();
|
|
2239
|
+
*
|
|
2240
|
+
* // Complex update with multiple operations
|
|
2241
|
+
* const result = await new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-A' })
|
|
2242
|
+
* .set({
|
|
2243
|
+
* status: 'OCCUPIED',
|
|
2244
|
+
* occupants: 3,
|
|
2245
|
+
* 'metadata.lastInspection': new Date().toISOString()
|
|
2246
|
+
* })
|
|
2247
|
+
* .add('securityBreaches', 1)
|
|
2248
|
+
* .deleteElementsFromSet('suitableDinosaurs', ['VELOCIRAPTOR'])
|
|
2249
|
+
* .condition(op => op.gt('securityLevel', 8))
|
|
2250
|
+
* .returnValues('ALL_NEW')
|
|
2251
|
+
* .execute();
|
|
2252
|
+
* ```
|
|
2253
|
+
*
|
|
2254
|
+
* @typeParam T - The type of item being updated
|
|
2255
|
+
*/
|
|
2256
|
+
declare class UpdateBuilder<T extends DynamoItem> {
|
|
2257
|
+
protected updates: UpdateAction[];
|
|
2258
|
+
protected options: UpdateOptions;
|
|
2259
|
+
protected readonly executor: UpdateExecutor<T>;
|
|
2260
|
+
protected readonly tableName: string;
|
|
2261
|
+
protected readonly key: PrimaryKeyWithoutExpression;
|
|
2262
|
+
constructor(executor: UpdateExecutor<T>, tableName: string, key: PrimaryKeyWithoutExpression);
|
|
2263
|
+
/**
|
|
2264
|
+
* Sets multiple attributes of an item using an object.
|
|
2265
|
+
*
|
|
2266
|
+
* @example
|
|
2267
|
+
* ```typescript
|
|
2268
|
+
* // Update multiple attributes
|
|
2269
|
+
* builder.set({
|
|
2270
|
+
* species: 'Tyrannosaurus Rex',
|
|
2271
|
+
* height: 20,
|
|
2272
|
+
* diet: 'CARNIVORE',
|
|
2273
|
+
* 'stats.threatLevel': 10
|
|
2274
|
+
* });
|
|
2275
|
+
* ```
|
|
2276
|
+
*/
|
|
2277
|
+
set(values: Partial<T>): UpdateBuilder<T>;
|
|
2278
|
+
/**
|
|
2279
|
+
* Sets a single attribute to a specific value.
|
|
2280
|
+
*
|
|
2281
|
+
* @example
|
|
2282
|
+
* ```typescript
|
|
2283
|
+
* // Set simple attributes
|
|
2284
|
+
* builder
|
|
2285
|
+
* .set('status', 'SLEEPING')
|
|
2286
|
+
* .set('lastFeeding', new Date().toISOString());
|
|
2287
|
+
*
|
|
2288
|
+
* // Set nested attributes
|
|
2289
|
+
* builder
|
|
2290
|
+
* .set('location.zone', 'RESTRICTED')
|
|
2291
|
+
* .set('stats.health', 100);
|
|
2292
|
+
* ```
|
|
2293
|
+
*/
|
|
2294
|
+
set<K extends Path<T>>(path: K, value: PathType<T, K>): UpdateBuilder<T>;
|
|
2295
|
+
/**
|
|
2296
|
+
* Removes an attribute from the item.
|
|
2297
|
+
*
|
|
2298
|
+
* @example
|
|
2299
|
+
* ```typescript
|
|
2300
|
+
* // Remove simple attributes
|
|
2301
|
+
* builder
|
|
2302
|
+
* .remove('temporaryTag')
|
|
2303
|
+
* .remove('previousLocation');
|
|
2304
|
+
*
|
|
2305
|
+
* // Remove nested attributes
|
|
2306
|
+
* builder
|
|
2307
|
+
* .remove('metadata.testData')
|
|
2308
|
+
* .remove('stats.experimentalMetrics');
|
|
2309
|
+
* ```
|
|
2310
|
+
*
|
|
2311
|
+
* @param path - The path to the attribute to remove
|
|
2312
|
+
* @returns The builder instance for method chaining
|
|
2313
|
+
*/
|
|
2314
|
+
remove<K extends Path<T>>(path: K): this;
|
|
2315
|
+
/**
|
|
2316
|
+
* Adds a value to a number attribute or adds elements to a set.
|
|
2317
|
+
*
|
|
2318
|
+
* @example
|
|
2319
|
+
* ```typescript
|
|
2320
|
+
* // Increment counters
|
|
2321
|
+
* builder
|
|
2322
|
+
* .add('escapeAttempts', 1)
|
|
2323
|
+
* .add('feedingCount', 1);
|
|
2324
|
+
*
|
|
2325
|
+
* // Add to sets
|
|
2326
|
+
* builder
|
|
2327
|
+
* .add('knownBehaviors', new Set(['PACK_HUNTING', 'AMBUSH_TACTICS']))
|
|
2328
|
+
* .add('visitedZones', new Set(['ZONE_A', 'ZONE_B']));
|
|
2329
|
+
* ```
|
|
2330
|
+
*
|
|
2331
|
+
* @param path - The path to the attribute to update
|
|
2332
|
+
* @param value - The value to add (number or set)
|
|
2333
|
+
* @returns The builder instance for method chaining
|
|
2334
|
+
*/
|
|
2335
|
+
add<K extends Path<T>>(path: K, value: PathType<T, K>): this;
|
|
2336
|
+
/**
|
|
2337
|
+
* Removes elements from a set attribute.
|
|
2338
|
+
*
|
|
2339
|
+
* @example
|
|
2340
|
+
* ```typescript
|
|
2341
|
+
* // Remove from sets using arrays
|
|
2342
|
+
* builder.deleteElementsFromSet(
|
|
2343
|
+
* 'allowedHabitats',
|
|
2344
|
+
* ['JUNGLE', 'COASTAL']
|
|
2345
|
+
* );
|
|
2346
|
+
*
|
|
2347
|
+
* // Remove from sets using Set DynamoItems
|
|
2348
|
+
* builder.deleteElementsFromSet(
|
|
2349
|
+
* 'knownBehaviors',
|
|
2350
|
+
* new Set(['NOCTURNAL', 'TERRITORIAL'])
|
|
2351
|
+
* );
|
|
2352
|
+
*
|
|
2353
|
+
* // Remove from nested sets
|
|
2354
|
+
* builder.deleteElementsFromSet(
|
|
2355
|
+
* 'stats.compatibleSpecies',
|
|
2356
|
+
* ['VELOCIRAPTOR', 'DILOPHOSAURUS']
|
|
2357
|
+
* );
|
|
2358
|
+
* ```
|
|
2359
|
+
*
|
|
2360
|
+
* @param path - The path to the set attribute
|
|
2361
|
+
* @param value - Elements to remove (array or Set)
|
|
2362
|
+
* @returns The builder instance for method chaining
|
|
2363
|
+
*/
|
|
2364
|
+
deleteElementsFromSet<K extends Path<T>>(path: K, value: PathSetElementType<T, K>[] | Set<PathSetElementType<T, K>>): this;
|
|
2365
|
+
/**
|
|
2366
|
+
* Adds a condition that must be satisfied for the update to succeed.
|
|
2367
|
+
*
|
|
2368
|
+
* @example
|
|
2369
|
+
* ```typescript
|
|
2370
|
+
* // Simple condition
|
|
2371
|
+
* builder.condition(op =>
|
|
2372
|
+
* op.eq('status', 'ACTIVE')
|
|
2373
|
+
* );
|
|
2374
|
+
*
|
|
2375
|
+
* // Health check condition
|
|
2376
|
+
* builder.condition(op =>
|
|
2377
|
+
* op.and([
|
|
2378
|
+
* op.gt('health', 50),
|
|
2379
|
+
* op.eq('status', 'HUNTING')
|
|
2380
|
+
* ])
|
|
2381
|
+
* );
|
|
2382
|
+
*
|
|
2383
|
+
* // Complex security condition
|
|
2384
|
+
* builder.condition(op =>
|
|
2385
|
+
* op.and([
|
|
2386
|
+
* op.attributeExists('securitySystem'),
|
|
2387
|
+
* op.eq('containmentStatus', 'SECURE'),
|
|
2388
|
+
* op.lt('aggressionLevel', 8)
|
|
2389
|
+
* ])
|
|
2390
|
+
* );
|
|
2391
|
+
*
|
|
2392
|
+
* // Version check (optimistic locking)
|
|
2393
|
+
* builder.condition(op =>
|
|
2394
|
+
* op.eq('version', currentVersion)
|
|
2395
|
+
* );
|
|
2396
|
+
* ```
|
|
2397
|
+
*
|
|
2398
|
+
* @param condition - Either a Condition DynamoItem or a callback function that builds the condition
|
|
2399
|
+
* @returns The builder instance for method chaining
|
|
2400
|
+
*/
|
|
2401
|
+
condition(condition: Condition | ((op: ConditionOperator<T>) => Condition)): this;
|
|
2402
|
+
/**
|
|
2403
|
+
* Sets which item attributes to include in the response.
|
|
2404
|
+
*
|
|
2405
|
+
* Available options:
|
|
2406
|
+
* - ALL_NEW: All attributes after the update (default)
|
|
2407
|
+
* - UPDATED_NEW: Only updated attributes, new values
|
|
2408
|
+
* - ALL_OLD: All attributes before the update
|
|
2409
|
+
* - UPDATED_OLD: Only updated attributes, old values
|
|
2410
|
+
* - NONE: No attributes returned
|
|
2411
|
+
*
|
|
2412
|
+
* @example
|
|
2413
|
+
* ```typescript
|
|
2414
|
+
* // Get complete updated dinosaur
|
|
2415
|
+
* const result = await builder
|
|
2416
|
+
* .set('status', 'SLEEPING')
|
|
2417
|
+
* .returnValues('ALL_NEW')
|
|
2418
|
+
* .execute();
|
|
2419
|
+
*
|
|
2420
|
+
* // Track specific attribute changes
|
|
2421
|
+
* const result = await builder
|
|
2422
|
+
* .set({
|
|
2423
|
+
* 'stats.health': 100,
|
|
2424
|
+
* 'stats.energy': 95
|
|
2425
|
+
* })
|
|
2426
|
+
* .returnValues('UPDATED_OLD')
|
|
2427
|
+
* .execute();
|
|
2428
|
+
*
|
|
2429
|
+
* if (result.item) {
|
|
2430
|
+
* console.log('Previous health:', result.item.stats?.health);
|
|
2431
|
+
* }
|
|
2432
|
+
* ```
|
|
2433
|
+
*
|
|
2434
|
+
* @param returnValues - Which attributes to return in the response
|
|
2435
|
+
* @returns The builder instance for method chaining
|
|
2436
|
+
*/
|
|
2437
|
+
returnValues(returnValues: "ALL_NEW" | "UPDATED_NEW" | "ALL_OLD" | "UPDATED_OLD" | "NONE"): this;
|
|
2438
|
+
/**
|
|
2439
|
+
* Generate the DynamoDB command parameters
|
|
2440
|
+
*/
|
|
2441
|
+
toDynamoCommand(): UpdateCommandParams;
|
|
2442
|
+
/**
|
|
2443
|
+
* Adds this update operation to a transaction.
|
|
2444
|
+
*
|
|
2445
|
+
* @example
|
|
2446
|
+
* ```typescript
|
|
2447
|
+
* const transaction = new TransactionBuilder(executor);
|
|
2448
|
+
*
|
|
2449
|
+
* // Update dinosaur status and habitat occupancy atomically
|
|
2450
|
+
* new UpdateBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
|
|
2451
|
+
* .set('location', 'PADDOCK_A')
|
|
2452
|
+
* .set('status', 'CONTAINED')
|
|
2453
|
+
* .withTransaction(transaction);
|
|
2454
|
+
*
|
|
2455
|
+
* new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-A' })
|
|
2456
|
+
* .add('occupants', 1)
|
|
2457
|
+
* .set('lastOccupied', new Date().toISOString())
|
|
2458
|
+
* .withTransaction(transaction);
|
|
2459
|
+
*
|
|
2460
|
+
* // Execute all operations atomically
|
|
2461
|
+
* await transaction.execute();
|
|
2462
|
+
* ```
|
|
2463
|
+
*
|
|
2464
|
+
* @param transaction - The transaction builder to add this operation to
|
|
2465
|
+
* @returns The builder instance for method chaining
|
|
2466
|
+
*/
|
|
2467
|
+
withTransaction(transaction: TransactionBuilder): void;
|
|
2468
|
+
/**
|
|
2469
|
+
* Gets a human-readable representation of the update command.
|
|
2470
|
+
*
|
|
2471
|
+
* @example
|
|
2472
|
+
* ```typescript
|
|
2473
|
+
* // Create complex update
|
|
2474
|
+
* const builder = new UpdateBuilder(executor, 'dinosaurs', { id: 'RAPTOR-001' })
|
|
2475
|
+
* .set({
|
|
2476
|
+
* status: 'HUNTING',
|
|
2477
|
+
* 'stats.health': 95,
|
|
2478
|
+
* 'behavior.lastObserved': new Date().toISOString()
|
|
2479
|
+
* })
|
|
2480
|
+
* .add('huntingSuccesses', 1)
|
|
2481
|
+
* .condition(op => op.gt('health', 50));
|
|
2482
|
+
*
|
|
2483
|
+
* // Debug the update
|
|
2484
|
+
* const debugInfo = builder.debug();
|
|
2485
|
+
* console.log('Update operation:', debugInfo);
|
|
2486
|
+
* ```
|
|
2487
|
+
*
|
|
2488
|
+
* @returns A readable representation of the update command with resolved expressions
|
|
2489
|
+
*/
|
|
2490
|
+
debug(): {
|
|
2491
|
+
raw: UpdateCommandParams;
|
|
2492
|
+
readable: {
|
|
2493
|
+
conditionExpression?: string;
|
|
2494
|
+
updateExpression?: string;
|
|
2495
|
+
filterExpression?: string;
|
|
2496
|
+
keyConditionExpression?: string;
|
|
2497
|
+
projectionExpression?: string;
|
|
2498
|
+
};
|
|
2499
|
+
};
|
|
2500
|
+
/**
|
|
2501
|
+
* Executes the update operation against DynamoDB.
|
|
2502
|
+
*
|
|
2503
|
+
* @example
|
|
2504
|
+
* ```typescript
|
|
2505
|
+
* try {
|
|
2506
|
+
* // Update dinosaur status with conditions
|
|
2507
|
+
* const result = await new UpdateBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
|
|
2508
|
+
* .set({
|
|
2509
|
+
* status: 'FEEDING',
|
|
2510
|
+
* lastMeal: new Date().toISOString(),
|
|
2511
|
+
* 'stats.hunger': 0
|
|
2512
|
+
* })
|
|
2513
|
+
* .add('feedingCount', 1)
|
|
2514
|
+
* .condition(op =>
|
|
2515
|
+
* op.and([
|
|
2516
|
+
* op.gt('stats.hunger', 80),
|
|
2517
|
+
* op.eq('status', 'HUNTING')
|
|
2518
|
+
* ])
|
|
2519
|
+
* )
|
|
2520
|
+
* .returnValues('ALL_NEW')
|
|
2521
|
+
* .execute();
|
|
2522
|
+
*
|
|
2523
|
+
* if (result.item) {
|
|
2524
|
+
* console.log('Updated dinosaur:', result.item);
|
|
2525
|
+
* }
|
|
2526
|
+
* } catch (error) {
|
|
2527
|
+
* // Handle condition check failure
|
|
2528
|
+
* console.error('Failed to update dinosaur:', error);
|
|
2529
|
+
* // Check if dinosaur wasn't hungry enough
|
|
2530
|
+
* if (error.name === 'ConditionalCheckFailedException') {
|
|
2531
|
+
* console.log('Dinosaur not ready for feeding');
|
|
2532
|
+
* }
|
|
2533
|
+
* }
|
|
2534
|
+
* ```
|
|
2535
|
+
*
|
|
2536
|
+
* @returns A promise that resolves to an DynamoItem containing the updated item (if returnValues is set)
|
|
2537
|
+
* @throws {ConditionalCheckFailedException} If the condition check fails
|
|
2538
|
+
* @throws {Error} If the update operation fails for other reasons
|
|
2539
|
+
*/
|
|
2540
|
+
execute(): Promise<{
|
|
2541
|
+
item?: T;
|
|
2542
|
+
}>;
|
|
2543
|
+
}
|
|
2544
|
+
|
|
2545
|
+
/**
|
|
2546
|
+
* Builder for creating DynamoDB condition check operations.
|
|
2547
|
+
* Use this builder when you need to:
|
|
2548
|
+
* - Verify item state without modifying it
|
|
2549
|
+
* - Ensure preconditions in transactions
|
|
2550
|
+
* - Implement optimistic locking patterns
|
|
2551
|
+
* - Validate business rules
|
|
2552
|
+
*
|
|
2553
|
+
* @example
|
|
2554
|
+
* ```typescript
|
|
2555
|
+
* // Check if dinosaur is ready for feeding
|
|
2556
|
+
* const check = new ConditionCheckBuilder('dinosaurs', { id: 'TREX-001' })
|
|
2557
|
+
* .condition(op =>
|
|
2558
|
+
* op.and([
|
|
2559
|
+
* op.eq('status', 'HUNTING'),
|
|
2560
|
+
* op.gt('stats.hunger', 80),
|
|
2561
|
+
* op.lt('stats.health', 100)
|
|
2562
|
+
* ])
|
|
2563
|
+
* )
|
|
2564
|
+
* .toDynamoCommand();
|
|
2565
|
+
*
|
|
2566
|
+
* // Check habitat security status
|
|
2567
|
+
* const securityCheck = new ConditionCheckBuilder('habitats', { id: 'PADDOCK-A' })
|
|
2568
|
+
* .condition(op =>
|
|
2569
|
+
* op.and([
|
|
2570
|
+
* op.eq('securityStatus', 'ACTIVE'),
|
|
2571
|
+
* op.attributeExists('lastInspection'),
|
|
2572
|
+
* op.lt('threatLevel', 5)
|
|
2573
|
+
* ])
|
|
2574
|
+
* )
|
|
2575
|
+
* .toDynamoCommand();
|
|
2576
|
+
* ```
|
|
2577
|
+
*/
|
|
2578
|
+
declare class ConditionCheckBuilder {
|
|
2579
|
+
private readonly key;
|
|
2580
|
+
private readonly tableName;
|
|
2581
|
+
private conditionExpression?;
|
|
2582
|
+
constructor(tableName: string, key: PrimaryKeyWithoutExpression);
|
|
2583
|
+
/**
|
|
2584
|
+
* Adds a condition that must be satisfied for the check to succeed.
|
|
2585
|
+
*
|
|
2586
|
+
* @example
|
|
2587
|
+
* ```typescript
|
|
2588
|
+
* // Check dinosaur health and behavior
|
|
2589
|
+
* builder.condition(op =>
|
|
2590
|
+
* op.and([
|
|
2591
|
+
* op.gt('stats.health', 50),
|
|
2592
|
+
* op.not(op.eq('status', 'SEDATED')),
|
|
2593
|
+
* op.lt('aggressionLevel', 8)
|
|
2594
|
+
* ])
|
|
2595
|
+
* );
|
|
2596
|
+
*
|
|
2597
|
+
* // Verify habitat conditions
|
|
2598
|
+
* builder.condition(op =>
|
|
2599
|
+
* op.and([
|
|
2600
|
+
* op.eq('powerStatus', 'ONLINE'),
|
|
2601
|
+
* op.between('temperature', 20, 30),
|
|
2602
|
+
* op.attributeExists('lastMaintenance')
|
|
2603
|
+
* ])
|
|
2604
|
+
* );
|
|
2605
|
+
*
|
|
2606
|
+
* // Check breeding conditions
|
|
2607
|
+
* builder.condition(op =>
|
|
2608
|
+
* op.and([
|
|
2609
|
+
* op.eq('species', 'VELOCIRAPTOR'),
|
|
2610
|
+
* op.gte('age', 3),
|
|
2611
|
+
* op.eq('geneticPurity', 100)
|
|
2612
|
+
* ])
|
|
2613
|
+
* );
|
|
2614
|
+
* ```
|
|
2615
|
+
*
|
|
2616
|
+
* @param condition - Either a Condition DynamoItem or a callback function that builds the condition
|
|
2617
|
+
* @returns The builder instance for method chaining
|
|
2618
|
+
*/
|
|
2619
|
+
condition<T extends DynamoItem>(condition: Condition | ((op: ConditionOperator<T>) => Condition)): this;
|
|
2620
|
+
/**
|
|
2621
|
+
* Generates the DynamoDB command parameters for direct execution.
|
|
2622
|
+
* Use this method when you want to:
|
|
2623
|
+
* - Execute the condition check as a standalone operation
|
|
2624
|
+
* - Get the raw DynamoDB command for custom execution
|
|
2625
|
+
* - Inspect the generated command parameters
|
|
2626
|
+
*
|
|
2627
|
+
* @example
|
|
2628
|
+
* ```ts
|
|
2629
|
+
* const command = new ConditionCheckBuilder('myTable', { id: '123' })
|
|
2630
|
+
* .condition(op => op.attributeExists('status'))
|
|
2631
|
+
* .toDynamoCommand();
|
|
2632
|
+
* // Use command with DynamoDB client
|
|
2633
|
+
* ```
|
|
2634
|
+
*
|
|
2635
|
+
* @throws {Error} If no condition has been set
|
|
2636
|
+
* @returns The DynamoDB command parameters
|
|
2637
|
+
*/
|
|
2638
|
+
private toDynamoCommand;
|
|
2639
|
+
/**
|
|
2640
|
+
* Adds this condition check operation to a transaction.
|
|
2641
|
+
*
|
|
2642
|
+
* @example
|
|
2643
|
+
* ```ts
|
|
2644
|
+
* const transaction = new TransactionBuilder();
|
|
2645
|
+
* new ConditionCheckBuilder('habitats', { id: 'PADDOCK-B' })
|
|
2646
|
+
* .condition(op => op.and([
|
|
2647
|
+
* op.eq('securityStatus', 'ACTIVE'),
|
|
2648
|
+
* op.lt('currentOccupants', 3),
|
|
2649
|
+
* op.eq('habitatType', 'CARNIVORE')
|
|
2650
|
+
* ]))
|
|
2651
|
+
* .withTransaction(transaction);
|
|
2652
|
+
* // Add dinosaur transfer operations
|
|
2653
|
+
* ```
|
|
2654
|
+
*
|
|
2655
|
+
* @param transaction - The transaction builder to add this operation to
|
|
2656
|
+
* @throws {Error} If no condition has been set
|
|
2657
|
+
* @returns The builder instance for method chaining
|
|
2658
|
+
*/
|
|
2659
|
+
withTransaction(transaction: TransactionBuilder): this;
|
|
2660
|
+
/**
|
|
2661
|
+
* Gets a human-readable representation of the condition check command
|
|
2662
|
+
* with all expression placeholders replaced by their actual values.
|
|
2663
|
+
*
|
|
2664
|
+
* @example
|
|
2665
|
+
* ```ts
|
|
2666
|
+
* const debugInfo = new ConditionCheckBuilder('dinosaurs', { id: 'TREX-001' })
|
|
2667
|
+
* .condition(op => op.and([
|
|
2668
|
+
* op.between('stats.health', 50, 100),
|
|
2669
|
+
* op.not(op.eq('status', 'SEDATED')),
|
|
2670
|
+
* op.attributeExists('lastFeedingTime')
|
|
2671
|
+
* op.eq('version', 1)
|
|
2672
|
+
* ]))
|
|
2673
|
+
* .debug();
|
|
2674
|
+
* console.log(debugInfo);
|
|
2675
|
+
* ```
|
|
2676
|
+
*
|
|
2677
|
+
* @returns A readable representation of the condition check command with resolved expressions
|
|
2678
|
+
*/
|
|
2679
|
+
debug(): {
|
|
2680
|
+
raw: ConditionCheckCommandParams;
|
|
2681
|
+
readable: {
|
|
2682
|
+
conditionExpression?: string;
|
|
2683
|
+
updateExpression?: string;
|
|
2684
|
+
filterExpression?: string;
|
|
2685
|
+
keyConditionExpression?: string;
|
|
2686
|
+
projectionExpression?: string;
|
|
2687
|
+
};
|
|
2688
|
+
};
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
/**
|
|
2692
|
+
* Configuration options for DynamoDB scan operations.
|
|
2693
|
+
* Extends the base FilterOptions.
|
|
2694
|
+
*/
|
|
2695
|
+
type ScanOptions = FilterOptions;
|
|
2696
|
+
/**
|
|
2697
|
+
* Function type for executing DynamoDB filter operations.
|
|
2698
|
+
* @typeParam T - The type of items being filtered
|
|
2699
|
+
*/
|
|
2700
|
+
type ScanExecutor<T extends DynamoItem> = (options: ScanOptions) => Promise<{
|
|
2701
|
+
items: T[];
|
|
2702
|
+
lastEvaluatedKey?: DynamoItem;
|
|
2703
|
+
}>;
|
|
2704
|
+
/**
|
|
2705
|
+
* Builder for creating DynamoDB scan operations.
|
|
2706
|
+
* Use this builder when you need to:
|
|
2707
|
+
* - Scan all items in a table
|
|
2708
|
+
* - Filter results based on non-key attributes
|
|
2709
|
+
* - Scan items on a Secondary Index (GSI)
|
|
2710
|
+
* - Implement pagination
|
|
2711
|
+
* - Project specific attributes
|
|
2712
|
+
*
|
|
2713
|
+
* The builder supports:
|
|
2714
|
+
* - Type-safe GSI selection
|
|
2715
|
+
* - Complex filter conditions
|
|
2716
|
+
* - Automatic pagination handling
|
|
2717
|
+
* - Consistent reads
|
|
2718
|
+
* - Attribute projection
|
|
2719
|
+
*
|
|
2720
|
+
* @example
|
|
2721
|
+
* ```typescript
|
|
2722
|
+
* // Simple scan with filtering
|
|
2723
|
+
* const result = await new ScanBuilder(executor)
|
|
2724
|
+
* .filter(op => op.eq('status', 'ACTIVE'))
|
|
2725
|
+
* .execute();
|
|
2726
|
+
*
|
|
2727
|
+
* // Scan with GSI and filtering
|
|
2728
|
+
* const result = await new ScanBuilder(executor)
|
|
2729
|
+
* .useIndex('status-index')
|
|
2730
|
+
* .filter(op => op.gt('securityLevel', 8))
|
|
2731
|
+
* .select(['id', 'capacity', 'currentOccupants'])
|
|
2732
|
+
* .limit(10)
|
|
2733
|
+
* .execute();
|
|
2734
|
+
*
|
|
2735
|
+
* // Scan with pagination
|
|
2736
|
+
* const paginator = new ScanBuilder(executor)
|
|
2737
|
+
* .filter(op => op.eq('type', 'INCIDENT'))
|
|
2738
|
+
* .paginate(25);
|
|
2739
|
+
*
|
|
2740
|
+
* while (paginator.hasNextPage()) {
|
|
2741
|
+
* const page = await paginator.getNextPage();
|
|
2742
|
+
* // Process page.items
|
|
2743
|
+
* }
|
|
2744
|
+
* ```
|
|
2745
|
+
*
|
|
2746
|
+
* @typeParam T - The type of items being scanned
|
|
2747
|
+
* @typeParam TConfig - The table configuration type for type-safe GSI selection
|
|
2748
|
+
*/
|
|
2749
|
+
declare class ScanBuilder<T extends DynamoItem, TConfig extends TableConfig = TableConfig> extends FilterBuilder<T, TConfig> implements ScanBuilderInterface<T, TConfig> {
|
|
2750
|
+
protected readonly executor: ScanExecutor<T>;
|
|
2751
|
+
constructor(executor: ScanExecutor<T>);
|
|
2752
|
+
/**
|
|
2753
|
+
* Creates a deep clone of this ScanBuilder instance.
|
|
2754
|
+
*
|
|
2755
|
+
* @returns A new ScanBuilder instance with the same configuration
|
|
2756
|
+
*/
|
|
2757
|
+
clone(): ScanBuilder<T, TConfig>;
|
|
2758
|
+
private deepCloneFilter;
|
|
2759
|
+
/**
|
|
2760
|
+
* Executes the scan against DynamoDB and returns a generator that behaves like an array.
|
|
2761
|
+
*
|
|
2762
|
+
* The generator automatically handles pagination and provides array-like methods
|
|
2763
|
+
* for processing results efficiently without loading everything into memory at once.
|
|
2764
|
+
*
|
|
2765
|
+
* @example
|
|
2766
|
+
* ```typescript
|
|
2767
|
+
* try {
|
|
2768
|
+
* // Find all dinosaurs with high aggression levels with automatic pagination
|
|
2769
|
+
* const results = await new ScanBuilder(executor)
|
|
2770
|
+
* .filter(op =>
|
|
2771
|
+
* op.and([
|
|
2772
|
+
* op.eq('status', 'ACTIVE'),
|
|
2773
|
+
* op.gt('aggressionLevel', 7)
|
|
2774
|
+
* ])
|
|
2775
|
+
* )
|
|
2776
|
+
* .execute();
|
|
2777
|
+
*
|
|
2778
|
+
* // Use like an array with automatic pagination
|
|
2779
|
+
* for await (const dinosaur of results) {
|
|
2780
|
+
* console.log(`Processing dangerous dinosaur: ${dinosaur.name}`);
|
|
2781
|
+
* }
|
|
2782
|
+
*
|
|
2783
|
+
* // Or convert to array and use array methods
|
|
2784
|
+
* const allItems = await results.toArray();
|
|
2785
|
+
* const criticalThreats = allItems.filter(dino => dino.aggressionLevel > 9);
|
|
2786
|
+
* const totalCount = allItems.length;
|
|
2787
|
+
* } catch (error) {
|
|
2788
|
+
* console.error('Security scan failed:', error);
|
|
2789
|
+
* }
|
|
2790
|
+
* ```
|
|
2791
|
+
*
|
|
2792
|
+
* @returns A promise that resolves to a ResultGenerator that behaves like an array
|
|
2793
|
+
*/
|
|
2794
|
+
execute(): Promise<ResultIterator<T, TConfig>>;
|
|
2795
|
+
}
|
|
2796
|
+
|
|
2797
|
+
export { BatchBuilder as B, ConditionCheckBuilder as C, DeleteBuilder as D, FilterBuilder as F, GetBuilder as G, PutBuilder as P, QueryBuilder as Q, ResultIterator as R, ScanBuilder as S, TransactionBuilder as T, UpdateBuilder as U, BatchError as a, type BatchResult as b, type DeleteOptions as c, type PutOptions as d, type QueryOptions as e, type TransactionOptions as f, type UpdateOptions as g, type BatchWriteOperation as h, type UpdateCommandParams as i, Paginator as j, type DeleteCommandParams as k, type PutCommandParams as l, type ConditionCheckCommandParams as m, type BaseBuilderInterface as n, type QueryBuilderInterface as o, type ScanBuilderInterface as p, type FilterBuilderInterface as q, type PaginationResult as r, type TransactionItem as s };
|