Skip to content

Instantly share code, notes, and snippets.

@marcieltorres
Created August 25, 2018 02:10
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 marcieltorres/edbadfecf6daa9286351ef0b365431aa to your computer and use it in GitHub Desktop.
Save marcieltorres/edbadfecf6daa9286351ef0b365431aa to your computer and use it in GitHub Desktop.
NodeJS: Validating s3 file with the AWS Lambda Function
//Using SDK
var aws = require('aws-sdk');
var s3 = new aws.S3();
//Define quais extensões serão aceitas no bucket
var _extensionsAllowed = ["txt", "csv"];
//Define tamanho máximo e mínimo que serão aceitos (em bytes)
var _minFileSize = 20; var _maxFileSize = (1024*1024*2);
//Define se deve copiar objeto para outro bucket
var _copyBucketName = "name-of-bucket"; //se não deve copiar para outro bucket, basta deixar como null
exports.handler = function(event, context) {
//Define string para retorno
var _strReturn = "";
//Verifica se o objeto existe (chamada através de evento no S3)
if ((event.Records[0]) && (event.Records[0].s3) && (event.Records[0].s3.bucket) && (event.Records[0].s3.object)){
//Recupera informações de bucket e do objeto
var _bucket = event.Records[0].s3.bucket.name;
var _key = event.Records[0].s3.object.key;
var _size = event.Records[0].s3.object.size ? event.Records[0].s3.object.size : 0;
if ((_bucket) && (_key)){
//Busca a extensão do arquivo
var _extFile = _key.split('.').pop();
//Se a extensão é válida então segue para próxima etapa da validação, caso contrário remove arquivo do bucket
if(_extensionsAllowed.indexOf(_extFile) !== -1){
//Verifica o tamanho do arquivo de acordo com os parâmetros definidos, senão remove
if((Math.round(_size) > _minFileSize) && (Math.round(_size) <= _maxFileSize)){
if(_copyBucketName){
copyObject(_copyBucketName, _key, _bucket);
_strReturn = "Arquivo " + _key + " permitido e copiado para o bucket " + _copyBucketName;
}
else {
_strReturn = "Arquivo " + _key + " permitido e mantido no bucket " + _bucket;
}
}
else{
deleteObject(_bucket, _key);
_strReturn = "Tamanho não permitido, arquivo " + _key + " foi removido automaticamente";
}
}
else{
deleteObject(_bucket, _key);
_strReturn = "Extensão não permitida, arquivo " + _key + " foi removido automaticamente";
}
}
else {
_strReturn = "Arquivo não encontrado";
}
}
else {
_strReturn = "Arquivo não encontrado ou evento não configurado";
}
//Retorno
callback(null, _strReturn);
};
function deleteObject(bucket, key){
s3.deleteObject({ Bucket: bucket, Key: key}, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
}
function copyObject(bucket, key, bucketSource){
s3.copyObject({Bucket: bucket, CopySource: encodeURIComponent(bucketSource + '/' + key), Key: key}, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment