Created
July 7, 2018 04:58
-
-
Save saki7/754eb313a3a2fc7f7f80cb2157198ab8 to your computer and use it in GitHub Desktop.
AWS Lambda script to set static asset (image, audio, etc.) "Cache-Control" metadata in S3
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
const aws = require('aws-sdk') | |
const s3 = new aws.S3({ apiVersion: '2006-03-01' }) | |
const svar_key = 'cache_control_script_version' | |
const svar_val = 7 | |
exports.handler = async (event, context) => { | |
// console.log('Received event:', JSON.stringify(event, null, 2)) | |
// Get the object from the event and show its content type | |
const bucket = event.Records[0].s3.bucket.name | |
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')) | |
console.log('target object: ' + bucket + '/' + key) | |
console.log(`fetching...`) | |
const data = await s3.headObject({Bucket: bucket, Key: key}).promise() | |
console.log('current Cache-Control: ', data.CacheControl) | |
const prev_svar = parseInt(data.Metadata[svar_key], 10) | |
console.log(`check: prev_svar ${prev_svar} >= svar ${svar_val}`) | |
// typeof data.CacheControl != 'undefined' | |
if (!!prev_svar && prev_svar >= svar_val) { | |
console.log('skipped: cache control already exists') | |
return context.done(null, 'skipped') | |
} else { | |
let ttl = 0 | |
if (key.match(/\.(css|js)$/)) { | |
ttl = 300 | |
} else if (key.match(/\.(ttf|woff|woff2|otf)$/)) { | |
ttl = 86400 | |
} else if (key.match(/favicon\.(ico|png)$/)) { | |
ttl = 86400 | |
} else if (data.ContentType.match(/^image\//)) { | |
ttl = 300 | |
} else if (data.ContentType.match(/^audio\//)) { | |
ttl = 86400 | |
} | |
if (ttl === 0) { | |
console.log('no matching criteria for target Cache-Control') | |
return context.done(null, 'skipped') | |
} | |
const params = { | |
Bucket: bucket, | |
CopySource: bucket + '/' + key, | |
Key: key, | |
CacheControl: `max-age=${ttl}`, | |
MetadataDirective: "REPLACE", | |
Metadata: Object.assign({}, data.Metadata, { | |
[svar_key]: svar_val.toString(), | |
}), | |
ContentType: data.ContentType, | |
} | |
try { | |
console.log(`setting TTL: ${ttl}`) | |
await s3.copyObject(params).promise() | |
} catch (e) { | |
return context.done('error', `failed to update: ${e}`) | |
} | |
return context.done(null, 'object updated successfully') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment