Created
October 11, 2024 17:47
-
-
Save mikebroberts/8737179a92f6e11494a02781329e1a11 to your computer and use it in GitHub Desktop.
Emptying / deleting all items in a DynamoDB table in TypeScript using the AWS Javascript SDK V3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BatchWriteCommand, DynamoDBDocumentClient, paginateScan } from '@aws-sdk/lib-dynamodb' | |
import { DynamoDBClient } from '@aws-sdk/client-dynamodb' | |
function filterKeys<T extends object>(object: T, keyPredicate: (key: string) => boolean) { | |
return object ? Object.fromEntries(Object.entries(object).filter(([key]) => keyPredicate(key))) : object | |
} | |
function selectKeys<T extends object>(object: T, keys: string[]) { | |
return filterKeys(object, (key) => keys.includes(key)) | |
} | |
export async function deleteAllItemsInTable(tableName: string, keyFields: string[]) { | |
const client = DynamoDBDocumentClient.from(new DynamoDBClient({})) | |
for await (const page of paginateScan({ client, pageSize: 25 }, { TableName: tableName })) { | |
process.stdout.write('.') | |
const items = page.Items | |
if (items) { | |
await client.send( | |
new BatchWriteCommand({ | |
RequestItems: { | |
[tableName]: items.map((item) => ({ | |
DeleteRequest: { | |
Key: selectKeys(item, keyFields) | |
} | |
})) | |
} | |
}) | |
) | |
} | |
} | |
} | |
// Example: | |
// deleteAllItemsInTable('my-table-name', ['PK', 'SK']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment