Created
July 25, 2024 13:55
-
-
Save benjaminparnell/5aaac6bfc7fa7b36f6693f90591d2e4c to your computer and use it in GitHub Desktop.
Update all records in a dynamodb table with some value
This file contains hidden or 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 { | |
DynamoDBDocument, | |
UpdateCommand, | |
paginateScan, | |
} from "@aws-sdk/lib-dynamodb"; | |
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; | |
const tableName = ""; | |
const dynamoClient = DynamoDBDocument.from(new DynamoDBClient({})); | |
interface RecordType { | |
email: string; | |
createdAt?: string; | |
} | |
const wait = (ms: number) => | |
new Promise((resolve) => setTimeout(() => resolve(true), ms)); | |
const run = async () => { | |
const paginator = paginateScan( | |
{ | |
client: dynamoClient, | |
pageSize: 50, | |
}, | |
{ | |
TableName: tableName, | |
} | |
); | |
let total = 0; | |
for await (const page of paginator) { | |
const promises = (page.Items as RecordType[]) | |
.filter((item) => !item.createdAt && item.createdAt !== null) | |
.map((item) => { | |
return dynamoClient.send( | |
new UpdateCommand({ | |
TableName: tableName, | |
Key: { | |
email: item.email, | |
}, | |
UpdateExpression: "SET createdAt = :createdAt", | |
ExpressionAttributeValues: { | |
":createdAt": null, | |
}, | |
}) | |
); | |
}); | |
total += promises.length; | |
console.log(`Updating ${promises.length} records (total: ${total})`); | |
if (promises.length !== 0) { | |
await Promise.all(promises); | |
await wait(1500); | |
} | |
} | |
}; | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment