Skip to content

Instantly share code, notes, and snippets.

@markusklems
Last active September 24, 2021 03:48
Show Gist options
  • Star 68 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save markusklems/1e7218d76d7583f1f7b3 to your computer and use it in GitHub Desktop.
Save markusklems/1e7218d76d7583f1f7b3 to your computer and use it in GitHub Desktop.
Short aws lambda sample program that puts an item into dynamodb
// create an IAM Lambda role with access to dynamodb
// Launch Lambda in the same region as your dynamodb region
// (here: us-east-1)
// dynamodb table with hash key = user and range key = datetime
console.log('Loading event');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
dynamodb.listTables(function(err, data) {
console.log(JSON.stringify(data, null, ' '));
});
var tableName = "chat";
var datetime = new Date().getTime().toString();
dynamodb.putItem({
"TableName": tableName,
"Item" : {
"user": {"S": event.user },
"date": {"S": datetime },
"msg": {"S": event.msg}
}
}, function(err, data) {
if (err) {
context.done('error','putting item into dynamodb failed: '+err);
}
else {
console.log('great success: '+JSON.stringify(data, null, ' '));
context.done('K THX BY');
}
});
};
// sample event
//{
// "user": "bart",
// "msg": "hey otto man"
//}
@dusterio
Copy link

there is no putItem() method in DocumentClient anymore: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property
There is put(), update(), etc instead

@juanvgarcia
Copy link

Plus, if you use the DocumentClient, you can use normal JSON objects and the SDK will handle the object model for you.

Therefore

dynamodbDocClient.put({
    'TableName': 'table',
    'Item': {
        'test': 'test',
        'number': 1
    }
}, function(err, data) {
    if (err) {
        console.log(err);
    } else {
        console.log(data);
    }
});

Should work perfectly fine.

@ryan-leap
Copy link

@deibid Thanks for the tip suggesting to use:

var doc = require('dynamodb-doc');
var dynamo = new doc.DynamoDB();

INSTEAD OF:

var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

I was getting "Task timed out after 3.00 seconds" on my DynamoDB calls until I followed your recommendation.

@jalbano
Copy link

jalbano commented Mar 17, 2018

In case anyone gets here and is still seeing the "Task timed out after 3.00 seconds" thing -- I had to move my require and new doc.DynamicDB() lines to the very top of the lambda code -- outside of the exports.handler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment