-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (62 loc) · 2.04 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const AWS = require('aws-sdk');
const util = require('util');
const async = require('async');
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = function(event, context, callback) {
// Read options from the event.
const srcBucket = event.Records[0].s3.bucket.name;
// Object key may have spaces or unicode non-ASCII characters.
const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
const dstBucket = process.env.COMPRESSED_BUCKET_NAME;
const dstKey = srcKey;
// Sanity check: validate that source and destination are different buckets.
if (srcBucket == dstBucket) {
callback("Source and destination buckets are the same.");
return;
}
// Infer the image type.
const typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
callback("Could not determine the image type.");
return;
}
const imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
callback('Unsupported image type: ${imageType}');
return;
}
async.waterfall([
function download(next) {
s3.getObject({
Bucket: srcBucket,
Key: srcKey
}, next);
},
function minify(imageObject, next) {
imagemin.buffer(imageObject.Body, {
plugins: [
imageminMozjpeg({quality: 70})
]
}).then(files => next(null, files, imageObject.ContentType))
.catch(err => console.log('minification error: ', err));
},
function upload(newImage, contentType, next) {
s3.putObject({
Bucket: dstBucket,
Key: dstKey,
Body: newImage,
ContentType: contentType,
}, next);
},
], function(err) {
if (err) {
console.log(err);
} else {
console.log(`Image compressed and uploaded to ${dstBucket}`);
}
callback(null, "message");
});
};