This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
83 lines (78 loc) · 2.06 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var async = require("async");
var AWS = require("aws-sdk");
var im = require("gm").subClass({imageMagick: true});
var s3 = new AWS.S3();
var CONFIG = require("./config.json");
function getImageType(objectContentType) {
switch (objectContentType) {
case "image/jpeg":
return "jpeg";
case "image/png":
return "png";
default:
throw new Error("Unsupported objectContentType " + objectContentType);
}
}
function cross(left, right) {
var res = [];
left.forEach(function(l) {
right.forEach(function(r) {
res.push([l, r]);
});
});
return res;
}
exports.handler = function(event, context, callback) {
console.log("event ", JSON.stringify(event));
async.mapLimit(event.Records, CONFIG.concurrency, function(record, cb) {
var originalKey = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
s3.getObject({
"Bucket": record.s3.bucket.name,
"Key": originalKey
}, function(err, data) {
if (err) {
cb(err);
} else {
cb(null, {
"originalKey": originalKey,
"contentType": data.ContentType,
"imageType": getImageType(data.ContentType),
"buffer": data.Body,
"record": record
});
}
});
}, function(err, images) {
if (err) {
context.callbackWaitsForEmptyEventLoop = false;
callback(err);
} else {
var resizePairs = cross(CONFIG.sizes, images);
async.eachLimit(resizePairs, CONFIG.concurrency, function(resizePair, cb) {
var config = resizePair[0];
var image = resizePair[1];
im(image.buffer).resize(config).toBuffer(image.imageType, function(err, buffer) {
if (err) {
cb(err);
} else {
s3.putObject({
"Bucket": image.record.s3.bucket.name.replace("-original", "-resized"),
"Key": config + "/" + image.originalKey,
"Body": buffer,
"ContentType": image.contentType
}, function(err) {
cb(err);
});
}
});
}, function(err) {
context.callbackWaitsForEmptyEventLoop = false;
if (err) {
callback(err);
} else {
callback();
}
});
}
});
};