Handy if you are using cloudfront, which is unable (sadly) to add extra headers based on S3 source files.
Runtime
Node.js 4.3
Handler
index.handler
Rest is up to you
Memory
128MB
Timeout
5 sec
VPC
No
Triggers
No -> I have set this up in the bucket config -> Events -> add notification for “Object created”
Code
[code:1:8244eb22f3]’use strict’;
// CONFIGURATION //////////////////////////////////////////////
var CacheControlHeader = ‘public, max-age=31536000’;
var lineBreak = ‘nn—————————————–nn’;
///////////////////////////////////////////////////////////////
console.log(’Loading function…’);
let aws = require(’aws-sdk’);
let s3 = new aws.S3({ apiVersion: ‘2006-03-01′ });
exports.handler = (event, context, callback) => {
const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/+/g, ” “));
var params = { Bucket: bucket, Key: key };
s3.getObject(params, (err, data) => {
if (err) {
console.log(err);
var message = lineBreak+’Error encountered!nnFailed to get object: s3://’+bucket+’/’+key +’.nnMake sure it is in the same region as this function!’+lineBreak;
console.log(message);
} else {
const mimeHeader = data.ContentType;
if (data.CacheControl != CacheControlHeader) {
var params = { Bucket: bucket, Key: key, CopySource: encodeURIComponent(bucket+’/’+key), ContentType: data.ContentType, CacheControl: CacheControlHeader, ‘Metadata’:{}, MetadataDirective: ‘REPLACE’ };
s3.copyObject(params, (err, data) => {
if (err) {
console.log(err);
message = lineBreak+’Error encountered!nnFailed to get object: s3://’+bucket+’/’+key +’.nnMake sure it is in the same region as this function!’+lineBreak;
console.log(message);
} else {
message = lineBreak+’Metadata updated successfully!nnOBJECT: s3://’+bucket+’/’+key+’nCONTENT-TYPE: ‘+mimeHeader+’nCACHE-CONTROL: ‘+CacheControlHeader+”+lineBreak;
console.log(message);
}
});
} else {
message = lineBreak+’Metadata already updated!nnOBJECT: s3://’+bucket+’/’+key+’nCONTENT-TYPE: ‘+mimeHeader+’nCACHE-CONTROL: ‘+CacheControlHeader+”+lineBreak;
console.log(message);
}
}
});
};[/code:1:8244eb22f3]
Leave a Reply