Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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"
//}
@deibid

This comment has been minimized.

Copy link

@deibid deibid commented Jul 27, 2015

Sweet guide, thanks.

If anybody's watching this after February 2015, 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 spent a lot of time very confused because things werent working out because of this.

@andelar

This comment has been minimized.

Copy link

@andelar andelar commented Jul 28, 2015

Hi, could you actually get this to work? I changed the example accordingly with subsequent correction of the variable name dynamodb.listTables to dynamo.listTables etc. Though I can't seem to get the Lambda to execute the dynamodb functions. Neither the err or data. Also I can't seem to figure out how to find what the error is, if permission related or otherwise.

@pittperson

This comment has been minimized.

Copy link

@pittperson pittperson commented Aug 1, 2015

To see the actual error change:
context.done('error','putting item into dynamodb failed: '+err);
to
context.done('error putting item into dynamodb failed: '+err);

The fix is to change:
"date": {"S": datetime },
to
"datetime": {"S": datetime },

@ScreamingHawk

This comment has been minimized.

Copy link

@ScreamingHawk ScreamingHawk commented Aug 25, 2015

I also had trouble with this. Item should be defined as follows:

"Item" : {
"user": event.user ,
"date": datetime,
"msg": event.msg
}

@pssubashps

This comment has been minimized.

Copy link

@pssubashps pssubashps commented Jan 6, 2016

i tried this.. i didn't get any errors,but data not getting inserted

then I tried this

console.log('Loading event');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB();

exports.handler = function(event, context) {
console.log("Request received:\n", JSON.stringify(event));
console.log("Context received:\n", JSON.stringify(context));

var tableName = "jobs";

dynamodb.putItem({
        "TableName": tableName,
        "Item": {
            "id": {
                "S": 5
            }, 
            "name": {
                "S": "user-1"
            }
        }
    }, function(err, data) {
        if (err) {
            context.fail('ERROR: Dynamo failed: ' + err);
        } else {
            console.log('Dynamo Success: ' + JSON.stringify(data, null, '  '));
            context.succeed('SUCCESS');
        }
    });

}

@abhis88

This comment has been minimized.

Copy link

@abhis88 abhis88 commented Jan 22, 2016

Even I didn't get any errors or data. Whatever is outside of the dynamodb block is getting printed fine.

@LamourBt

This comment has been minimized.

Copy link

@LamourBt LamourBt commented Feb 12, 2016

A lot has been changed in the AWSDynamoDB for Lambda. There is an working example


`console.log('Loading function');
      var doc = require('dynamodb-doc');
      var db = new doc.DynamoDB();
exports.handler = function(event, context) 
{
     var username  = event.username;
     var email = event.email;
     var userId = event.userId;
    console.log(username + "," + email +","+ userId);
var tableName = "User";
var item = {
     "username":username,
     "email":  email,
     "userId": userId
};
 var params = {
     TableName:tableName, 
     Item: item
 };
     console.log(params);
 db.putItem(params,function(err,data){
     if (err) console.log(err);
     else console.log(data);
 });
};`

And the test event code
{
"username":"admin",
"email":"admin@admin.com",
"userId": "AD87S"
}

@markusklems

This comment has been minimized.

Copy link
Owner Author

@markusklems markusklems commented Mar 19, 2016

Sorry guys, didn't look at this gist for a while. Thanks for the update @LamourBt

I have built a little sample application yesterday with the serverless framwork, lambda (nodejs), api gateway and dynamodb: https://github.com/markusklems/serverless-node-dynamodb-example Maybe the code helps and is more up to date than the one in this gist.

@u84six

This comment has been minimized.

Copy link

@u84six u84six commented Jul 21, 2016

How do you write records to the account database? I've been able to successfully do this with a local version, but how can I add a record to the remotely hosted database?

@lakshmantgld

This comment has been minimized.

Copy link

@lakshmantgld lakshmantgld commented Sep 12, 2016

How to return the inserted item? I want to return the inserted item as response.

@tetreault

This comment has been minimized.

Copy link

@tetreault tetreault commented Oct 6, 2016

@LamourBt your example is non-functional and it also doesn't align with the AWS Dynamo docs.

@martimatix

This comment has been minimized.

Copy link

@martimatix martimatix commented Oct 19, 2016

Hi guys, thanks to everyone that's contributed to this thread. It was helpful in getting things to work. I got writes to Dynamodb working using the Serverless framework. Link to gist below. 👇

https://gist.github.com/martimatix/06481e1321ab99bf4a501705235b261f

@glidenz

This comment has been minimized.

Copy link

@glidenz glidenz commented Nov 15, 2016

Hi

I found this tutorial most helpful nut I now find myself wanting to take it a step further by using less hardcoding of the Item values if possible.

Consider some incoming data that is not consistent in the types of data being received. Is it possible to iterate thru the JSON to determine the names of the items and then use them instead of hardcoding them?

ie

dynamodb.putItem({
"TableName": tableName,
"Item" : {
event1.name: {"S": event.1.data },
event2.name: {"S": event.2.data },
event3.name: {"S": event.3.data}
}

@dusterio

This comment has been minimized.

Copy link

@dusterio dusterio commented Apr 27, 2017

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

This comment has been minimized.

Copy link

@juanvgarcia juanvgarcia commented May 20, 2017

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

This comment has been minimized.

Copy link

@ryan-leap ryan-leap commented Jul 19, 2017

@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

This comment has been minimized.

Copy link

@jalbano 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
You can’t perform that action at this time.