I am working on aws lambda ,I am trying to put an Item using the lambda function with node.js.
I have following code with me..
var AWS = require('aws-sdk');
var dynamoDBConfiguration = {
"accessKeyId": "AccessKey",
"secretAccessKey": "Secratekey",
"region": "us-west-2"
};
AWS.config.update(dynamoDBConfiguration);
var dd = new AWS.DynamoDB();
var tableName = 'product_bhavik';
exports.handler = function(event, context) {
putItem = function(itemName,prod_Id, prod_Name, prod_Desc, prod_Price) {
console.log(" putItem Function Called");
var item = {
'itemName': { 'S': itemName },
'microtime': { 'N': new Date().getTime().toString() }
};
if (prod_Id) item.prod_Id = { 'N': prod_Id.toString()};
if (prod_Name) item.prod_Name = { 'S': prod_Name };
if (prod_Desc) item.prod_Desc = { 'S': prod_Desc };
if (prod_Price) item.prod_Price = { 'N': prod_Price.toString()};
console.log("Data: %j",item);
var response = dd.putItem({
'TableName': tableName,
'Item': item
}, function(err, data) {
err && console.log("Error in putItem "+err);
});
};
putItem('Item1',1, 'Laptop', 'Laptop for the IT users',10000);
context.succeed("Successfully Inserted");
}
when I am testing this code in logs there is no error, still I am not able to put an Item to the Dynamodb table,can you please help me to put an item to the dynamodb table by finding the problem with my way or can you suggest other way to use lambda to put item.
I think your most immediate problem is that you are calling context.succeeded()
before the response from DynamoDB. Lambda stops execution if you do this, without waiting for the response.
Also, I recommend adding a try/catch wrapper to see if anything goes wrong not reported in the DynamoDB callback. Try something like this:
exports.handler = function(event, context) {
try {
putItem = function(itemName,prod_Id, prod_Name, prod_Desc, prod_Price) {
console.log(" putItem Function Called");
var item = {
'itemName': { 'S': itemName },
'microtime': { 'N': new Date().getTime().toString() }
};
if (prod_Id) item.prod_Id = { 'N': prod_Id.toString()};
if (prod_Name) item.prod_Name = { 'S': prod_Name };
if (prod_Desc) item.prod_Desc = { 'S': prod_Desc };
if (prod_Price) item.prod_Price = { 'N': prod_Price.toString()};
console.log("Data: %j",item);
var response = dd.putItem({
'TableName': tableName,
'Item': item
}, function(err, data) {
if (err) {
context.fail("Error in putItem "+err);
} else {
context.succeed("Successfully Inserted");
}
});
};
putItem('Item1',1, 'Laptop', 'Laptop for the IT users',10000);
} catch (error) {
context.fail("Caught: " + error);
}
}
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