-
Notifications
You must be signed in to change notification settings - Fork 18
/
optimize.js
41 lines (34 loc) · 1007 Bytes
/
optimize.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
"use strict";
const AWS = require("aws-sdk");
const sharp = require("sharp");
const { basename, extname } = require("path");
const S3 = new AWS.S3();
module.exports.handle = async ({ Records: records }, context) => {
try {
await Promise.all(
records.map(async record => {
const { key } = record.s3.object;
const image = await S3.getObject({
Bucket: process.env.bucket,
Key: key
}).promise();
const optimized = await sharp(image.Body)
.resize(1280, 720, { fit: "inside", withoutEnlargement: true })
.toFormat("jpeg", { progressive: true, quality: 50 })
.toBuffer();
await S3.putObject({
Body: optimized,
Bucket: process.env.bucket,
ContentType: "image/jpeg",
Key: `compressed/${basename(key, extname(key))}.jpg`
}).promise();
})
);
return {
statusCode: 301,
body: { ok: true }
};
} catch (err) {
return err;
}
};