console.log('starting function');
var dynamodb = new AWS.DynamoDB();
var AWS = require('aws-sdk');
exports.handler = function (e, ctx, callback) {
var params = {
Item: {
"Name": {
S: "Dalton Warden"
},
"PhoneNumber": {
S: "796-353-1416",
}
},
ReturnConsumedCapacity: "TOTAL",
TableName: "CustomerInfo"
};
dynamodb.putItem(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
};
I'm pretty new to lambda and dynamoDB but i'm trying to send data to a table I have set up. I've been through amazon's documentation and looked for similar instances on this site and The formatting looks like it would return the correct JSON but I'm still having trouble. The error I'm getting is Cannot read property 'DynamoDB' of undefined".
Please change the order of the below statements as mentioned below (first AWS and then dynamodb).
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB();
Related
I am trying to enter the data in AWS Dynamo DB through the AWS Lambda function using AWS HTTP API. FYI The data type of the parameter (Id) originally in Dynamo DB is Number but it is taking as String while parsing JSON data, so I have written "Number" beside "Id" parameter in order to convert it to "Number". When I am trying to run this lambda function I am getting this error. Please help, Thanks!
Lambda function:
payload: { "Id": $input.json('$.Id') "name": $input.json('$.name')
console.log('starting function');
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = function(event, ctx, callback) {
var params = {
Item: {
Id: Number(event.Id),
name: event.name
},
TableName: 'Test'
};
console.log(params)
docClient.put(params, function(err, data) {
if(err) {
callback(err, null);
} else{
callback(null, data);
}
});
}
Error log:
Look at the logs.
Your event.Id value is "NaN" which means "not a number".
Also event.name is "undefined".
So your problem is occuring here:
exports.handler = function(event, ctx, callback) {
Your event object is not populated with the values you are expecting.
The payload should be proper JSON and look something like:
{
"id": "6",
"name": "Test Name"
}
To achieve this, in your POST from your front-end code you could use something like:
data: JSON.stringify({"id": $('#Id').val(), "name": $('#name').val()})
Make sure that $('#Id').val() and $('#name').val() actually have proper values.
I am using the aws-sdk within Node and trying to get an item from a DynamoDB table but it prints just Success {} and not the actual content of the item. Does anyone know how to get the actual content of the item?
The Node script I am using is the following:
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'ap-southeast-2'});
// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params = {
TableName: 'test_table',
Key: {
'TWEET_KEY' : {S: 'Test'}
},
ProjectionExpression: 'ATTRIBUTE_NAME'
};
// Call DynamoDB to read the item from the table
ddb.getItem(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data.Item);
}
});
and the actual data within the DynamoDB test_table which I'm trying to get is as follows:
Thank you very much!
Here - ProjectionExpression: 'ATTRIBUTE_NAME', you need to set the attribute names that you need to get, or just remove it to get the whole record content.
I am playing the aws mobilehub with react-native and I was hoping that it can speed up the backend hosting for me.
However, I cannot get its backend API working. After a long run with their docs, I pin down the problem between its lambda function and dynamodb service.
Any thoughts are greatly appreciated!
Problem#1
As the titled says: my aws lambda functions can request its dynamodb but has no response.
What went wrong here?
Or how can I get debug info from AWS dynamodb? (I gg and enabled Cloudtrial but it doesn't seem to have operation logs of the dynamodb too.)
Lambda side
Here I have the simplest node.js 6.10 codes:
const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});
const dynamodb = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context, callback) {
var responseCode = 200;
var requestBody, httpMethod, res;
console.log("request: " + JSON.stringify(event));
// Request Body
requestBody = event.body;
/*testing dynamodb with put*/
console.log("PUT begins");
let putItemParams2 = {
TableName: "xxxx-mobilehub-xxxx-Test",//tableName
Item: {businessId:'putItemParams2r3',test:'yooo', hmm:'hhhh'}
};
console.log("putItemParams2: ",putItemParams2);
dynamodb.put(putItemParams2, (err, data) => {
console.log("putItemParams2");
if (err) console.log("dynamodb err: ",err, err.stack); // an error occurred
else console.log("dynamodb data: ",data); // successful response
});
console.log("PUT end");
var response = {
statusCode: responseCode
//....
};
...
//comment out context.succeed here to avoid program termination before intended.
//console.log("response: " + JSON.stringify(response))
//context.succeed(response);
};
Logs
When the previouse codes are triggered, from AWS CloudWatch I can see logs:
START RequestId: 3d7c5f7f-1b98-11e8-ad00-93a6d10c8f4e Version: $LATEST
[timestamp] PUT begins
[timestamp] putItemParams2: { TableName: 'xxx-mobilehub-xxxx-Test',
Item: { businessId: 'putItemParams2r3', test: 'yooo', hmm: 'hhhh'}}
[timestamp] put end
END RequestId: 3d7c5f7f-1b98-11e8-ad00-93a6d10c8f4e
So no err, no data, no response. I checked my dynamodb and there is nothing insert.
Extra info
condition#1: this dynamodb table has public access since I want to rule out the auth problem.
condition#2: I ensure that my lambda function has access to these tables. e.g. arn:aws:dynamodb::xxxx:table/xxxx-mobilehub-xxxx- allow everything
condition#3: I build myself a simple node.js to execute the (aws-sdk)and this server works perfectly fine with the same code..
I am able to "get" &"put" items int & out from my dynamodb table.
Problem#2
my react-native code use 'aws-amplify-react-native'. Which the API.put is fine and the lambda function is at least receiving the api call (from problem#1).
However, API.get returns me 403 error, and the lambda function doesn't even has log for this operation..
async function getBusiness(){
const path = "/Test";
const api = "TestCRUD";
let queryGetBusiness = {body: {userId: "hmmm"}};
try {
let apiResponse = await API.get(api, path, queryGetBusiness)//.then((data)=>{console.log(data)});
let apiResponseJson = await JSON.stringify(apiResponse);
console.log("response from saving Business: " + apiResponseJson);
}
catch (e) {console.log(e);}
}
P.S.(AWS could do much better with this mobilehub.. their documentation is lacking details and awsmobile cloud-api invoke has some problems I guess.)
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-2' });
const dynamodb = new AWS.DynamoDB.DocumentClient();
exports.handler = function (event, context, callback) {
var responseCode = 200;
var requestBody, httpMethod, res;
console.log("request: " + JSON.stringify(event));
// Request Body
requestBody = event.body;
/*testing dynamodb with put*/
console.log("PUT begins");
let putItemParams2 = {
TableName: "xxxx-mobilehub-xxxx-Test",//tableName
Item: { businessId: 'putItemParams2r3', test: 'yooo', hmm: 'hhhh' }
};
console.log("putItemParams2: ", putItemParams2);
dynamodb.put(putItemParams2, (err, data) => {
console.log("putItemParams2");
if (err) console.log("dynamodb err: ", err, err.stack); // an error occurred
else {
console.log("dynamodb data: ", data);
context.succeed(response);
}
// Call these here
console.log("PUT end");
});
//console.log("response: " + JSON.stringify(response))
};
Make sure you call context.succeed inside the callback function. Like above.
You can also just use the third argument to handler function - callback instead of context.succeed like callback(null, response);
I have written simple Lambda function to scan data from dynamodb, but data is getting retrieved with error message tag and lambda function shows message as execution failed
var AWS = require('aws-sdk');
var DOC = require("dynamodb-doc");
var dynamo = new DOC.DynamoDB();
exports.handler = function (event, context, callback) {
var params = {
TableName: "Movies",
// ProjectionExpression: "#yr, Movie",
FilterExpression: "#yr = :thisyear",
ExpressionAttributeNames: {
"#yr": "year",
},
ExpressionAttributeValues: {
":thisyear" : 2009
}
};
dynamo.scan(params, function(err, data){
if (err){
callback("error occoured");
}
else{
callback(JSON.stringify(data.Items));
}
});
};
Result
{
"errorMessage": "[{\"year\":2009,\"Movie\":\"Jab tak hai jaan\"}]"
}
nodejs callback are typically error-first callbacks. It means that the first parameter is the error message and the second parameter is the result. So when returning the result you need to pass null as the first argument.
eg: callback(null, JSON.stringify(data.Items));
Please refer this article
I am trying to get my Alexa skill programmed in Node.js to make a query in my dynamodb table.
I have this in the header:
var AWS = require("aws-sdk");
AWS.config.update({
region: "us-west-1",
});
var dynamodb = new AWS.DynamoDB();
var docClient = new AWS.DynamoDB.DocumentClient();
And in one of my intends I call this:
var params = {
TableName: 'TblName',
Key:{
"User": 'TestUser'
}
};
docClient.get(params, function(err, data) {
if (err) {
this.emit(':tell', 'A');
} else {
this.emit(':tell', 'B');
}
});
Now I thought that this would either throw an error, return A or return B. But for some reason, I simply get no response at all. Is there any obvious thing I am doing wrong?
Edit: If I change the table name to a non-existing one, I still don't get an error message or an A output. It just executes the rest of the code.
Edit: I guess one problem is identical to this one. I will close as soon as I got it fully working.