How do I use batchWriteItem with Node.js to query AWS DynamoDB?
Solution 1
This should get you what you need.
- Create a New Lambda Function
- Select Node Version 6
- Select a Role or Create a New one that has DynamoDB Access to Write!
- Open Created Function in the Web Console
-
Paste the Snippet Bellow into the Cloud 9 Editor
const AWS = require('aws-sdk/global'); exports.handler = (event, context, callback) => { // The event parameter is the input to your lambda function console.log(JSON.stringify(event)); let lambdaInput = event['PROPERTY_NAME_DEFINED_IN_POST']; let games = []; let documentClient = new AWS.DynamoDB.DocumentClient(); lambda.forEach(item => { games.push({ PutRequest: { Item: { gamepk: item['gamepk'], user: item['user'], result: item['result'] } } }); }); let params = { RequestItems: { 'TABLE_NAME': games } }; documentClient.batchWrite(params, function(err, data) { if (err) { callback(err); } else { callback(null, data); } }); }
Save the Function and then you are going to want to select the drop down at the top that says 'Select a Test Event' and then select 'Configure Test Events'.
This will open a new dialog, just save the JSON that is in the main text area and give the test a Name and Save it.
Now select that test that you just made from the 'Select a Test Event' drop down and then click 'Test' in the top right.
This documentation could be found at AWS Javascript SDK
Solution 2
As an additional help for the answer , you can use an environment variable and use it in the following way:
const MI_TABLE = process.env.MI_TABLE
let params = {
RequestItems: {
[ MI_TABLE ] : games
}
};
return await batchWrite(params);
rolo
Updated on June 16, 2022Comments
-
rolo almost 2 years
I'm new to AWS and I'm having problems trying to develop a simple Lambda function with Node.js. In DynamoDB, I have a table named
Game
with 3 attributes:gamepk
,user
,result
. In just one single execution of the Lambda function, I want to insert a collection ofgame
elements (the number of elements in the collection could vary). I had been reading some tutorials and it said I should usebatchWriteItem
, but because the collection of Game elements is variable I don't know how to proceed.Could somebody write a function in Node.js that solves my problem?
An example of the JSON that the lambda function receives is this one:
{ "games": [{ "gamepk": "1", "user": "rolo", "result": "1-0" }, { "gamepk": "2", "user": "jhon", "result": "1-1" } ] }