-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
100 lines (92 loc) · 2.8 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* eslint-env node */
"use strict";
const AWS = require('aws-sdk');
const gm = require('gm').subClass({ imageMagick: true });
const config = require('./config');
const dimensions = {
avatar: [16, 24, 32, 48, 64, 72, 96, 128, 256, 320, 480, 512, 640, 960],
content: [120, 240, 320, 480, 640, 960]
};
exports.handler = (event, context, callback) => {
const s3 = new AWS.S3();
const bucket = event.Records[0].s3.bucket.name;
const destinationBucket = config.bucketName;
const keyLocationInBucket = event.Records[0].s3.object.key;
const splittedKeyLocation = keyLocationInBucket.split("/");
const imageType = splittedKeyLocation[0];
const keyLocationInDestinationBucket = splittedKeyLocation.slice(0, splittedKeyLocation.length-1).join("/");
const resize = (imageType, imageBuffer, width, height, next) => {
if (imageType === "avatar") {
gm(imageBuffer)
.resize(width)
.gravity("center")
.crop(width, height)
.toBuffer('JPG', next);
} else {
gm(imageBuffer)
.resize(width)
.gravity("center")
.toBuffer('JPG', next);
}
};
const getObjectFromS3 = () => {
return new Promise((resolve, reject) => {
s3.getObject({
Bucket: bucket,
Key: keyLocationInBucket
}, (err, data) => {
if (err) {
reject("someting went wrong while getting the uploaded image: " + err);
} else {
resolve(data);
}
});
});
};
const putObjectToS3 = (body) => {
const imageResizePromises = [];
dimensions[imageType].forEach((dimension) => {
imageResizePromises.push(
new Promise((resolve, reject) => {
resize(imageType, body, dimension, dimension, function(err, responseBuffer) {
if (err) {
reject("something went wrong while resizing image to " + dimension + ": " + err);
} else {
console.log("Done resizing image to dimension: " + dimension);
resolve([responseBuffer, dimension]);
}
});
})
);
});
Promise.all(imageResizePromises)
.then((resizedImages) => {
// resizedImageAndDimension => Type: Object(Array) Format: [ImageBuffer, Dimension(Integer)]
resizedImages.forEach((resizedImageAndDimension) => {
s3.putObject({
Bucket: destinationBucket,
Key: keyLocationInDestinationBucket + "/" + resizedImageAndDimension[1] + '.jpg',
Body: resizedImageAndDimension[0]
}, (err, data) => {
if (err) {
console.log("something went wrong while uploading image of dimension " + resizedImageAndDimension[1] + ": " + err);
} else {
console.log("Done uploading resized image of dimension: " + resizedImageAndDimension[1]);
console.log(data);
}
});
});
})
.catch((err) => {
console.log(err);
});
};
getObjectFromS3()
.then((data) => {
console.log(data);
putObjectToS3(data.Body);
})
.catch((err) => {
console.log(err);
});
}