| 7 | type BatchWritable = Put | Delete; |
| 8 | |
| 9 | export class BatchWrite { |
| 10 | private batchWriteItems: BatchWritable[] = []; |
| 11 | returnConsumedCapacity?: ReturnConsumedCapacity |
| 12 | returnItemCollectionMetrics?: ReturnItemCollectionMetrics |
| 13 | |
| 14 | public get items() { return this.batchWriteItems; } |
| 15 | public get length() { return this.batchWriteItems.length; } |
| 16 | |
| 17 | constructor(private client: DynamoDBDocumentClient) { } |
| 18 | |
| 19 | push(...writes: BatchWritable[]): BatchWrite { this.batchWriteItems.push(...writes); return this; } |
| 20 | async run(): Promise<BatchWriteCommandOutput> { return await this.client.send(new BatchWriteCommand(this.build())); } |
| 21 | |
| 22 | put(tableName: string, item: any) { |
| 23 | const put = new Put(tableName, item).client(this.client); |
| 24 | this.push(put); |
| 25 | } |
| 26 | |
| 27 | delete(tableName: string, key: any) { |
| 28 | const d = new Delete(tableName, key).client(this.client); |
| 29 | this.push(d); |
| 30 | } |
| 31 | |
| 32 | build(): BatchWriteCommandInput { |
| 33 | const puts = this.batchWriteItems.filter((p): p is Put => p instanceof Put) |
| 34 | const deletes = this.batchWriteItems.filter((p): p is Delete => p instanceof Delete) |
| 35 | const tableNames = [...puts, ...deletes].map(p => p.tableName).filter((v, i, a) => a.indexOf(v) === i) |
| 36 | |
| 37 | const input: BatchWriteCommandInput = { |
| 38 | RequestItems: tableNames.reduce((acc, tableName) => { |
| 39 | const putRequests = puts.filter(p => p.tableName === tableName).map(p => { return { PutRequest: { Item: p.build().Item } } }) |
| 40 | const deleteRequests = deletes.filter(p => p.tableName === tableName).map(p => { return { DeleteRequest: { Key: p.key } } }) |
| 41 | acc[tableName] = [...putRequests, ...deleteRequests] |
| 42 | return acc |
| 43 | }, {} as { [key: string]: WriteRequest[] }) |
| 44 | } |
| 45 | |
| 46 | if (this.returnConsumedCapacity) input.ReturnConsumedCapacity = this.returnConsumedCapacity |
| 47 | if (this.returnItemCollectionMetrics) input.ReturnItemCollectionMetrics = this.returnItemCollectionMetrics |
| 48 | |
| 49 | return input |
| 50 | } |
| 51 | } |
nothing calls this directly
no outgoing calls
no test coverage detected