Skip to content

Instantly share code, notes, and snippets.

@NutterzUK
Created September 15, 2017 20:55
Show Gist options
  • Save NutterzUK/4061a73baf717c8a2ac3fc28c4b71a04 to your computer and use it in GitHub Desktop.
Save NutterzUK/4061a73baf717c8a2ac3fc28c4b71a04 to your computer and use it in GitHub Desktop.
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
// Your bucket name and key here. Note that it should be in the same region as your lambda.
var bucket = "nutbrownweight"; // TODO REPLACE THIS!
var key = "weight.txt";
// Values passed in to the Lambda
var weight = event.weight;
var date = event.date;
// Create params object for AWS sdk call to S3.
var params = {
Bucket : bucket,
Key : key,
}
// Retrieve the object from S3.
s3.getObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
// Parse the contents of the object.
var response = JSON.parse(data.Body.toString('utf-8'));
var toPush = {
"weight": weight,
"date": date
}
// Add the new record to the array.
response.push(toPush);
// Write it back to S3.
putObjectToS3(bucket, key, response);
callback(null, 'Success');
}
});
};
function putObjectToS3(bucket, key, data){
var params = {
Bucket : bucket,
Key : key,
Body : JSON.stringify(data)
}
s3.putObject(params, function(err, data) {
if (err) {
callback(err);
throw err;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment