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 of game elements (the number of elements in the collection could vary).
I had been reading some tutorials and it said I should use batchWriteItem, 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"
            }
        ]
    }
                This should get you what you need.
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
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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With