-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (35 loc) · 1.02 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
const sharp = require("sharp");
const aws = require("aws-sdk");
const s3 = new aws.S3();
const Bucket = "sopt26";
const transforms = [
{ name: "w_200", width: 200 },
{ name: "w_400", width: 400 }
];
exports.handler = async (event, context, callback) => {
const key = event.Records[0].s3.object.key;
const sanitizedKey = key.replace(/\+/g, " ");
const parts = sanitizedKey.split("/");
const filename = parts[parts.length - 1];
try {
const image = await s3.getObject({ Bucket, Key: sanitizedKey }).promise();
await Promise.all(
transforms.map(async item => {
const resizedImg = await sharp(image.Body)
.rotate()
.resize({ width: item.width })
.toBuffer();
return await s3
.putObject({
Bucket,
Body: resizedImg,
Key: `images/${item.name}/${filename}`
})
.promise();
})
);
callback(null, `Success: ${filename}`);
} catch (err) {
callback(`Error resizing files: ${err}`);
}
};