I have a lambda written in node.js where i want to push the data to my dynamodb table. My end goal is for my api request to pull in the response and then push the results in the items section directly into dynamodb but at the moment my lambda is only pulling through the query and the createmessage function is being ignored (currently testing with static data). I presume my code is muddled somehow so need some help on how to have this running correctly, please see below:
// Loads in the AWS SDK
const AWS = require('aws-sdk');
// Creates the document client specifing the region
// The tutorial's table is 'in eu-west-2'
const ddb = new AWS.DynamoDB.DocumentClient({region: 'eu-west-2'});
exports.handler = async (event, context, callback) => {
// Captures the requestId from the context message
const requestId = context.awsRequestId;
// Handle promise fulfilled/rejected states
await createMessage(requestId).then(() => {
callback(null, {
statusCode: 201,
body: '',
headers: {
'Access-Control-Allow-Origin' : '*'
}
});
}).catch((err) => {
console.error(err)
})
};
// Function createMessage
// Writes message to DynamoDb table Message
function createMessage(requestId) {
const params = {
TableName: 'splunk-lambda',
Item: {
'id' : '101',
'message' : 'Hello from lambda'
}
}
return ddb.put(params).promise();
}
var request = require('request');
var options = {
'method': 'POST',
'url': 'myurl',
'headers': {
'x-api-key': 'my-api-key',
'Content-Type': 'text/plain'
},
body: 'query my graphql query'
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
my response from the lambda:
Test Event Name
test
Response
null
Function Logs
{my graphql response}
END RequestId: bdf23337-ca51-4f8b-868c-314f4d048055
CodePudding user response:
Based on the comments.
The issues was caused by using async handler. This leads to your function to finish before it has a chance run all its code.
One way to overcome this you can wrap your code in the handler in new Promise
as shown in the AWS docs.