Há mais exemplos do AWS SDK disponíveis no repositório do GitHub Documento de Exemplos do AWS SDK
Exemplos do DynamoDB usando o SDK para JavaScript (v2)
Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK para JavaScript (v2) com o DynamoDB.
Ações são trechos de código de programas maiores e devem ser executadas em contexto. Embora as ações mostrem como chamar perfis de serviço individuais, você pode ver as ações no contexto em seus cenários relacionados.
Cenários são exemplos de código que mostram como realizar tarefas específicas chamando várias funções dentro de um serviço ou combinadas com outros Serviços da AWS.
Cada exemplo inclui um link para o código-fonte completo, em que você pode encontrar instruções sobre como configurar e executar o código.
Ações
O código de exemplo a seguir mostra como usar BatchGetItem.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { RequestItems: { TABLE_NAME: { Keys: [ { KEY_NAME: { N: "KEY_VALUE_1" } }, { KEY_NAME: { N: "KEY_VALUE_2" } }, { KEY_NAME: { N: "KEY_VALUE_3" } }, ], ProjectionExpression: "KEY_NAME, ATTRIBUTE", }, }, }; ddb.batchGetItem(params, function (err, data) { if (err) { console.log("Error", err); } else { data.Responses.TABLE_NAME.forEach(function (element, index, array) { console.log(element); }); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em BatchGetItem na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar BatchWriteItem.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { RequestItems: { TABLE_NAME: [ { PutRequest: { Item: { KEY: { N: "KEY_VALUE" }, ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" }, ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" }, }, }, }, { PutRequest: { Item: { KEY: { N: "KEY_VALUE" }, ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" }, ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" }, }, }, }, ], }, }; ddb.batchWriteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Para obter mais detalhes da API, consulte BatchWriteItem na Referência da API do AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar CreateTable.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { AttributeDefinitions: [ { AttributeName: "CUSTOMER_ID", AttributeType: "N", }, { AttributeName: "CUSTOMER_NAME", AttributeType: "S", }, ], KeySchema: [ { AttributeName: "CUSTOMER_ID", KeyType: "HASH", }, { AttributeName: "CUSTOMER_NAME", KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, TableName: "CUSTOMER_LIST", StreamSpecification: { StreamEnabled: false, }, }; // Call DynamoDB to create the table ddb.createTable(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Table Created", data); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em CreateTable na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar DeleteItem.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. Exclua um item de uma tabela.
// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Key: { KEY_NAME: { N: "VALUE" }, }, }; // Call DynamoDB to delete the item from the table ddb.deleteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });Exclua um item de uma tabela usando o cliente de documento do DynamoDB.
// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { Key: { HASH_KEY: VALUE, }, TableName: "TABLE", }; docClient.delete(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em DeleteItem na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar DeleteTable.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: process.argv[2], }; // Call DynamoDB to delete the specified table ddb.deleteTable(params, function (err, data) { if (err && err.code === "ResourceNotFoundException") { console.log("Error: Table not found"); } else if (err && err.code === "ResourceInUseException") { console.log("Error: Table in use"); } else { console.log("Success", data); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em DeleteTable na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar DescribeTable.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: process.argv[2], }; // Call DynamoDB to retrieve the selected table descriptions ddb.describeTable(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Table.KeySchema); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em DescribeTable na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar GetItem.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. Obtenha um item de uma tabela.
// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Key: { KEY_NAME: { N: "001" }, }, ProjectionExpression: "ATTRIBUTE_NAME", }; // Call DynamoDB to read the item from the table ddb.getItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Item); } });Obtenha um item de uma tabela usando o cliente de documento do DynamoDB.
// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { TableName: "EPISODES_TABLE", Key: { KEY_NAME: VALUE }, }; docClient.get(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Item); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em GetItem na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar ListTables.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); // Call DynamoDB to retrieve the list of tables ddb.listTables({ Limit: 10 }, function (err, data) { if (err) { console.log("Error", err.code); } else { console.log("Table names are ", data.TableNames); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em ListTables na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar PutItem.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. Coloque um item em uma tabela.
// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "CUSTOMER_LIST", Item: { CUSTOMER_ID: { N: "001" }, CUSTOMER_NAME: { S: "Richard Roe" }, }, }; // Call DynamoDB to add the item to the table ddb.putItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });Coloque um item em uma tabela usando o cliente de documento do DynamoDB.
// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Item: { HASHKEY: VALUE, ATTRIBUTE_1: "STRING_VALUE", ATTRIBUTE_2: VALUE_2, }, }; docClient.put(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em PutItem na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar Query.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { ExpressionAttributeValues: { ":s": 2, ":e": 9, ":topic": "PHRASE", }, KeyConditionExpression: "Season = :s and Episode > :e", FilterExpression: "contains (Subtitle, :topic)", TableName: "EPISODES_TABLE", }; docClient.query(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Items); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em Query na Referência da API AWS SDK para JavaScript.
-
O código de exemplo a seguir mostra como usar Scan.
- SDK para JavaScript (v2)
-
nota
Há mais no GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository
. // Load the AWS SDK for Node.js. var AWS = require("aws-sdk"); // Set the AWS Region. AWS.config.update({ region: "REGION" }); // Create DynamoDB service object. var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); const params = { // Specify which items in the results are returned. FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e", // Define the expression attribute value, which are substitutes for the values you want to compare. ExpressionAttributeValues: { ":topic": { S: "SubTitle2" }, ":s": { N: 1 }, ":e": { N: 2 }, }, // Set the projection expression, which are the attributes that you want. ProjectionExpression: "Season, Episode, Title, Subtitle", TableName: "EPISODES_TABLE", }; ddb.scan(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); data.Items.forEach(function (element, index, array) { console.log( "printing", element.Title.S + " (" + element.Subtitle.S + ")" ); }); } });-
Para obter mais informações, consulte o Guia do desenvolvedor do AWS SDK para JavaScript.
-
Consulte detalhes da API em Scan na Referência da API AWS SDK para JavaScript.
-
Cenários
O exemplo de código a seguir mostra como invocar uma função do AWS Lambda em um navegador.
- SDK para JavaScript (v2)
-
É possível criar uma aplicação baseada em navegador que usa uma função do AWS Lambda para atualizar uma tabela do Amazon DynamoDB com seleções de usuário.
Para obter o código-fonte completo e instruções sobre como configurar e executar o exemplo, consulte o exemplo completo no GitHub
. Serviços usados neste exemplo
DynamoDB
Lambda