|
| 1 | +import { dynamoClient, docClient, createTable } from './common/dynamo' |
| 2 | +import { log } from './common/log' |
| 3 | +import { users, protectClient } from './common/protect' |
| 4 | +import { BatchGetCommand, BatchWriteCommand } from '@aws-sdk/lib-dynamodb' |
| 5 | +import { protectDynamoDB } from '@cipherstash/protect-dynamodb' |
| 6 | + |
| 7 | +const tableName = 'UsersBulkOperations' |
| 8 | + |
| 9 | +type User = { |
| 10 | + pk: string |
| 11 | + email: string |
| 12 | +} |
| 13 | + |
| 14 | +const main = async () => { |
| 15 | + await createTable({ |
| 16 | + TableName: tableName, |
| 17 | + AttributeDefinitions: [ |
| 18 | + { |
| 19 | + AttributeName: 'pk', |
| 20 | + AttributeType: 'S', |
| 21 | + }, |
| 22 | + ], |
| 23 | + KeySchema: [ |
| 24 | + { |
| 25 | + AttributeName: 'pk', |
| 26 | + KeyType: 'HASH', |
| 27 | + }, |
| 28 | + ], |
| 29 | + }) |
| 30 | + |
| 31 | + const protectDynamo = protectDynamoDB({ |
| 32 | + protectClient, |
| 33 | + }) |
| 34 | + |
| 35 | + const items = [ |
| 36 | + { |
| 37 | + // `pk` won't be encrypted because it's not included in the `users` protected table schema. |
| 38 | + pk: 'user#1', |
| 39 | + // `email` will be encrypted because it's included in the `users` protected table schema. |
| 40 | + email: 'abc@example.com', |
| 41 | + }, |
| 42 | + { |
| 43 | + pk: 'user#2', |
| 44 | + email: 'def@example.com', |
| 45 | + }, |
| 46 | + ] |
| 47 | + |
| 48 | + const encryptResult = await protectDynamo.bulkEncryptModels(items, users) |
| 49 | + |
| 50 | + if (encryptResult.failure) { |
| 51 | + throw new Error(`Failed to encrypt items: ${encryptResult.failure.message}`) |
| 52 | + } |
| 53 | + |
| 54 | + const putRequests = encryptResult.data.map( |
| 55 | + (item: Record<string, unknown>) => ({ |
| 56 | + PutRequest: { |
| 57 | + Item: item, |
| 58 | + }, |
| 59 | + }), |
| 60 | + ) |
| 61 | + |
| 62 | + log('encrypted items', encryptResult) |
| 63 | + |
| 64 | + const batchWriteCommand = new BatchWriteCommand({ |
| 65 | + RequestItems: { |
| 66 | + [tableName]: putRequests, |
| 67 | + }, |
| 68 | + }) |
| 69 | + |
| 70 | + await dynamoClient.send(batchWriteCommand) |
| 71 | + |
| 72 | + const batchGetCommand = new BatchGetCommand({ |
| 73 | + RequestItems: { |
| 74 | + [tableName]: { |
| 75 | + Keys: [{ pk: 'user#1' }, { pk: 'user#2' }], |
| 76 | + }, |
| 77 | + }, |
| 78 | + }) |
| 79 | + |
| 80 | + const getResult = await docClient.send(batchGetCommand) |
| 81 | + |
| 82 | + const decryptedItems = await protectDynamo.bulkDecryptModels<User>( |
| 83 | + getResult.Responses?.[tableName], |
| 84 | + users, |
| 85 | + ) |
| 86 | + |
| 87 | + log('decrypted items', decryptedItems) |
| 88 | +} |
| 89 | + |
| 90 | +main() |
0 commit comments