Skip to content

Instantly share code, notes, and snippets.

@yossale
Created January 29, 2019 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yossale/79336973df47f69dd8cdf21aed17c082 to your computer and use it in GitHub Desktop.
Save yossale/79336973df47f69dd8cdf21aed17c082 to your computer and use it in GitHub Desktop.
S3 read / copy / delete file
const aws = require('aws-sdk');
const s3 = new aws.S3({apiVersion: '2006-03-01'});
const LambdaLog = require('lambda-log').LambdaLog;
const log = new LambdaLog({meta: {environment: process.env.ENVIRONMENT}});
async function deleteObject(bucket, currentPath) {
var params = {
Bucket: bucket,
Delete: {
Objects: [
{
Key: currentPath
}
]
}
};
log.info(`Deleting file: ${JSON.stringify(params)}`);
return s3.deleteObjects(params).promise();
}
async function copyToNewLocation(bucket, currentPath, updateId) {
var params = {
Bucket: bucket,
Key: `updates/${updateId}/${Date.now()}`,
CopySource: `${bucket}/${currentPath}`
};
log.info(`Copying file: ${JSON.stringify(params)}`);
return s3.copyObject(params).promise();
}
var main = async (event, context, callback) => {
aws.config.logger = console;
log.info('Received event:', JSON.stringify(event, null, 2));
const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
const params = {
Bucket: bucket,
Key: key,
};
log.info("Event info: " + JSON.stringify(params));
try {
const data = await s3.getObject(params).promise();
const content = data.Body.toString('UTF-8');
let groupId = content.match(/Update Id: (\d+),/);
const copyRes = await copyToNewLocation(bucket, key, groupId[1]);
const deleteRes = await deleteObject(bucket, key);
callback(null, "Success");
} catch (err) {
const message = `Error getting object ${key} from bucket ${bucket}.`;
log.error(message);
callback(err);
}
};
exports.handler = main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment