I am creating a lambda function which I've tied to API gateway and my code doesn't seem to fire the s3.putObject event.
I can console.log the AWS, s3, params variables with no problems but when trying to use the putObject function, nothing fires...the rest of my code simply seems to run.
Does anyone know what I might need to do?
I've set a region on my s3 instance, an API version Logged out my variables Checked cloudwatch logs for changes
exports.handler = async (event) => {
const AWS = require('aws-sdk');
const s3 = new AWS.S3({region: "us-east-1", apiVersion: '2006-03-01'});
const params = {
Bucket: bucketName,
Key: 'file.txt',
ContentType: 'text/plain',
Body: JSON.stringify(event)};
// The below doesn't seem to run or log out
s3.putObject(params).promise().then(data => {
console.log('complete:PUT Object',data);
})
.catch(err => {
console.log('failure:PUT Object', err);
});
return JSON.stringify(event);
};
I expect to be able to go into my s3 bucket and see a file uploaded. Instead its empty
Because you're using exports.handler = async (event) in your code, you're using async/await (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
Within an async function you can use the await syntax to make a promise to a synchronous call:
try {
const res = await s3.upload(params, options).promise();
console.log('complete:', res);
} catch(err) {
console.log('error:', err);
}
This is a modern approach to callbacks and it's consistent (no mixture of callbacks and async functions).
You aren't waiting for the promise to return before telling lambda to return a result. Promises are great if you have a heap of chaining, but in this simple case, a call back should be enough.
Also if you are using async you need to make sure the runtime is 8.10 or above.
exports.handler = async (event, context, callback) => {
const AWS = require('aws-sdk');
const s3 = new AWS.S3({region: "us-east-1", apiVersion: '2006-03-01'});
const params = {
Bucket: bucketName,
Key: 'file.txt',
ContentType: 'text/plain',
Body: JSON.stringify(event)};
console.log(JSON.stringify(event));
// The below doesn't seem to run or log out
s3.upload(params, options, function(err, data) {
console.log(err, data);
if(!err) {
callback(null, "All Good");
}
else {
callback(err);
}
});
};
A little more reading on the context object. https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
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