@incdevco/framework
Version:
node.js lambda framework
146 lines (86 loc) • 3.08 kB
JavaScript
var crypto = require('crypto');
var AWS = require('aws-sdk');
var es = require('event-stream');
var gutil = require('gulp-util');
var Promise = require('bluebird');
var defaultContentType = 'application/octet-stream';
module.exports = function (config) {
'use strict';
var prefix;
var cf;
var s3;
config = config || {};
defaultContentType = config.defaultContentType
|| defaultContentType;
prefix = config.prefix || 'cloud-formation-templates/';
cf = config.cf || new AWS.CloudFormation();
s3 = config.s3 || new AWS.S3();
return es.map(function (file, done) {
var md5Hash = crypto.createHash('md5')
.update(file.contents)
.digest('hex');
var eTag = '"' + md5Hash + '"';
var key = prefix + file.path.replace(file.base, '');
s3.headObject({
Bucket: config.bucket,
Key: key
}).promise()
.then(function (result) {
//gutil.log(key, eTag, result.ETag);
if (eTag === result.ETag) {
// no file change, do not upload
//gutil.log('not changed', key);
return false;
} else {
// file has changed, upload
//gutil.log('uploading', key);
return true;
}
}, function (exception) {
//console.log('bucket', config.bucket);
//console.log('key', key);
//console.log(JSON.stringify(exception, null, 2));
if (exception.code === 'NotFound') {
return true;
}
throw exception;
})
.then(function (upload) {
if (upload) {
return s3.putObject({
Body: file.contents,
Bucket: config.bucket,
Key: key
}).promise()
.then(function (result) {
gutil.log('uploaded', key, result.VersionId);
function validateTemplate() {
return cf.validateTemplate({
TemplateURL: 'https://s3-'
+ AWS.config.region + '.amazonaws.com/'
+ config.bucket + '/' + key
}).promise()
.catch(function (exception) {
if (exception.code === 'Throttling') {
console.log('validateTemplate', 'Throttling');
return Promise.delay(1000)
.then(function () {
return validateTemplate();
});
}
gutil.log('validateTemplate', key, exception.message);
throw exception;
});
}
return validateTemplate();
});
} else {
return false;
}
})
.then(function () {
done();
})
.catch(done);
});
};