Below is a simple Lambda function that will write/update/fetch a file on S3. You'll need to provision your Lambda and S3 resources first or the execution will fail. This code was written for Node.js 8.10 Lambda in Javascript
console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({apiVersion: '2006-03-01'});
exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
if (event.httpMethod == "GET") {
return await getFile(callback);
} else if (event.httpMethod == "PUT") {
return await updateFile(event.body, callback);
}
};
/**
* Fetch the file from s3
* */
async function getFile(callback) {
const bucket = process.env.S3_BUCKET_NAME;
const key = process.env.S3_KEY;
const params = {
Bucket: bucket,
Key: key,
};
try {
const object = await s3.getObject(params).promise();
var file = object.Body.toString('ascii');
var response = {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": file,
"isBase64Encoded": false
};
callback(null, response);
} catch (err) {
const message = `Error getting object ${key} from bucket ${bucket}.` +
` Make sure they exist and your bucket is in the same region as this` +
`function. Error : ${err}`;
var response = {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": JSON.stringify(message),
"isBase64Encoded": false
};
console.log(message);
callback(null, response);
throw new Error(message);
}
}
/**
* Update the File stored in S3
* */
async function updateFile(body, callback) {
const bucket = process.env.S3_BUCKET_NAME;
const key = process.env.S3_KEY;
var params = {
Body: body,
Bucket: bucket,
Key: key
};
try {
const status = await s3.putObject(params).promise();
console.log("status: ", status); // successful response
var response = {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": JSON.stringify({status}),
"isBase64Encoded": false
};
callback(null, response);
} catch (err) {
const message = `Error putting object ${key} in bucket ${bucket}. Error : ${err}`;
var response = {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": message,
"isBase64Encoded": false
};
console.log(message);
callback(null, response);
throw new Error(message);
}
}