Created
October 11, 2017 11:08
-
-
Save veloxy/a5ace11fe6b360fb85c40794d0bc63fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
let aws = require('aws-sdk'); | |
let s3 = new aws.S3({apiVersion: '2006-03-01'}); | |
module.exports.cacheControl = (event) => { | |
// Bucket name & File path | |
const bucket = event.Records[0].s3.bucket.name; | |
const key = decodeURIComponent(event.Records[0].s3.object.key).replace(/\+/g, ' '); | |
let cacheDuration = 0; | |
// Set image cache for 1 month | |
if (key.match(/\.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$/)) { | |
cacheDuration = 6696000; | |
} | |
// More checks for other file types (js, css, fonts, ..) here | |
// ... | |
// No cache needed, do nothing. | |
if (cacheDuration <= 0) { | |
return; | |
} | |
let cacheControlHeader = 'max-age=' + cacheDuration; | |
// Get the file so we cacn check the meta data. | |
s3.getObject(params, (err, data) => { | |
// Something went wrong or file already has the cache control meta data, don't do anything. | |
if (err || data.CacheControl == cacheControlHeader) { | |
return; | |
} | |
let params = { | |
Bucket: bucket, | |
Key: key, | |
CopySource: encodeURIComponent(bucket + '/' + key), | |
ContentType: data.ContentType, | |
CacheControl: cacheControlHeader, | |
Metadata: {}, | |
MetadataDirective: 'REPLACE' | |
}; | |
// Overwrite the file. | |
s3.copyObject(params, (err, data) => { | |
// Something went wrong, don't do anything. | |
if (err) { | |
return; | |
} | |
console.log('Metadata updated successfully!'); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment