Skip to content

Instantly share code, notes, and snippets.

@benjaminparnell
Created July 25, 2024 13:55
Show Gist options
  • Save benjaminparnell/5aaac6bfc7fa7b36f6693f90591d2e4c to your computer and use it in GitHub Desktop.
Save benjaminparnell/5aaac6bfc7fa7b36f6693f90591d2e4c to your computer and use it in GitHub Desktop.
Update all records in a dynamodb table with some value
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