-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathbatch-write.js
60 lines (48 loc) · 1.95 KB
/
batch-write.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { fileURLToPath } from "node:url";
// snippet-start:[dynamodb.JavaScript.movies.batchwriteV3]
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
BatchWriteCommand,
DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";
import { readFileSync } from "node:fs";
// These modules are local to our GitHub repository. We recommend cloning
// the project from GitHub if you want to run this example.
// For more information, see https://github.com/awsdocs/aws-doc-sdk-examples.
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import { chunkArray } from "@aws-doc-sdk-examples/lib/utils/util-array.js";
const dirname = dirnameFromMetaUrl(import.meta.url);
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
export const main = async () => {
const file = readFileSync(
`${dirname}../../../../../resources/sample_files/movies.json`,
);
const movies = JSON.parse(file.toString());
// chunkArray is a local convenience function. It takes an array and returns
// a generator function. The generator function yields every N items.
const movieChunks = chunkArray(movies, 25);
// For every chunk of 25 movies, make one BatchWrite request.
for (const chunk of movieChunks) {
const putRequests = chunk.map((movie) => ({
PutRequest: {
Item: movie,
},
}));
const command = new BatchWriteCommand({
RequestItems: {
// An existing table is required. A composite key of 'title' and 'year' is recommended
// to account for duplicate titles.
BatchWriteMoviesTable: putRequests,
},
});
await docClient.send(command);
}
};
// snippet-end:[dynamodb.JavaScript.movies.batchwriteV3]
// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}