| 44 | const log = (msg) => console.log(`[SCENARIO] ${msg}`); |
| 45 | |
| 46 | export const main = async () => { |
| 47 | /** |
| 48 | * Create a table. |
| 49 | */ |
| 50 | |
| 51 | const createTableCommand = new CreateTableCommand({ |
| 52 | TableName: tableName, |
| 53 | // This example performs a large write to the database. |
| 54 | // Set the billing mode to PAY_PER_REQUEST to |
| 55 | // avoid throttling the large write. |
| 56 | BillingMode: BillingMode.PAY_PER_REQUEST, |
| 57 | // Define the attributes that are necessary for the key schema. |
| 58 | AttributeDefinitions: [ |
| 59 | { |
| 60 | AttributeName: "year", |
| 61 | // 'N' is a data type descriptor that represents a number type. |
| 62 | // For a list of all data type descriptors, see the following link. |
| 63 | // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors |
| 64 | AttributeType: "N", |
| 65 | }, |
| 66 | { AttributeName: "title", AttributeType: "S" }, |
| 67 | ], |
| 68 | // The KeySchema defines the primary key. The primary key can be |
| 69 | // a partition key, or a combination of a partition key and a sort key. |
| 70 | // Key schema design is important. For more info, see |
| 71 | // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html |
| 72 | KeySchema: [ |
| 73 | // The way your data is accessed determines how you structure your keys. |
| 74 | // The movies table will be queried for movies by year. It makes sense |
| 75 | // to make year our partition (HASH) key. |
| 76 | { AttributeName: "year", KeyType: "HASH" }, |
| 77 | { AttributeName: "title", KeyType: "RANGE" }, |
| 78 | ], |
| 79 | }); |
| 80 | |
| 81 | log("Creating a table."); |
| 82 | const createTableResponse = await client.send(createTableCommand); |
| 83 | log(`Table created: ${JSON.stringify(createTableResponse.TableDescription)}`); |
| 84 | |
| 85 | // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. |
| 86 | // You can't write to a table before it's active. |
| 87 | log("Waiting for the table to be active."); |
| 88 | await waitUntilTableExists({ client }, { TableName: tableName }); |
| 89 | log("Table active."); |
| 90 | |
| 91 | /** |
| 92 | * Add a movie to the table. |
| 93 | */ |
| 94 | |
| 95 | log("Adding a single movie to the table."); |
| 96 | // PutCommand is the first example usage of 'lib-dynamodb'. |
| 97 | const putCommand = new PutCommand({ |
| 98 | TableName: tableName, |
| 99 | Item: { |
| 100 | // In 'client-dynamodb', the AttributeValue would be required (`year: { N: 1981 }`) |
| 101 | // 'lib-dynamodb' simplifies the usage ( `year: 1981` ) |
| 102 | year: 1981, |
| 103 | // The preceding KeySchema defines 'title' as our sort (RANGE) key, so 'title' |