-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (38 loc) · 1.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const AWS = require("aws-sdk");
const sharp = require('sharp');
var THUMBNAIL_KEY_PREFIX = "thumbnails/";
var ALLOWED_FILETYPES = ['png', 'jpg', 'jpeg', 'tiff', 'gif'];
var s3 = new AWS.S3();
exports.handler = async (event, context) => {
if (!event.Records[0].s3){
return;
}
console.log(event.Records[0].s3.bucket.name);
console.log(event.Records[0].s3.object.key);
let bucket = event.Records[0].s3.bucket.name;
let srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
let dstKey = THUMBNAIL_KEY_PREFIX + srcKey.replace(/\.\w+$/, ".png");
let fileType = srcKey.match(/\.\w+$/);
console.log(bucket, srcKey, dstKey, fileType);
if(srcKey.indexOf(THUMBNAIL_KEY_PREFIX) === 0) {
return;
}
if (fileType === null) {
console.error("Invalid filetype for key: " + srcKey);
return;
}
fileType = fileType[0].substr(1);
if (ALLOWED_FILETYPES.indexOf(fileType.toLowerCase()) === -1) {
console.error("Invalid filetype: " + fileType);
return;
}
let params = {Bucket: bucket, Key: srcKey};
let response = await s3.getObject(params).promise();
let buffer = await sharp(response.Body).resize(40).png().toBuffer();
await s3.putObject({
Bucket: bucket,
Key: dstKey,
Body: buffer,
ContentType: "image/png",
}).promise();
};