-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.mjs
62 lines (55 loc) · 1.56 KB
/
index.mjs
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
import {
S3Client,
GetObjectCommand,
PutObjectCommand,
} from "@aws-sdk/client-s3";
import sharp from "sharp";
const S3 = new S3Client();
const DEST_BUCKET = process.env.DEST_BUCKET;
const THUMBNAIL_WIDTH = 200; // px
const SUPPORTED_FORMATS = {
jpg: true,
jpeg: true,
png: true,
};
export const handler = async (event, context) => {
const { eventTime, s3 } = event.Records[0];
const srcBucket = s3.bucket.name;
// Object key may have spaces or unicode non-ASCII characters
const srcKey = decodeURIComponent(s3.object.key.replace(/\+/g, " "));
const ext = srcKey.replace(/^.*\./, "").toLowerCase();
console.log(`${eventTime} - ${srcBucket}/${srcKey}`);
if (!SUPPORTED_FORMATS[ext]) {
console.log(`ERROR: Unsupported file type (${ext})`);
return;
}
// Get the image from the source bucket
try {
const { Body, ContentType } = await S3.send(
new GetObjectCommand({
Bucket: srcBucket,
Key: srcKey,
})
);
const image = await Body.transformToByteArray();
// resize image
const outputBuffer = await sharp(image).resize(THUMBNAIL_WIDTH).toBuffer();
// store new image in the destination bucket
await S3.send(
new PutObjectCommand({
Bucket: DEST_BUCKET,
Key: srcKey,
Body: outputBuffer,
ContentType,
})
);
const message = `Successfully resized ${srcBucket}/${srcKey} and uploaded to ${DEST_BUCKET}/${srcKey}`;
console.log(message);
return {
statusCode: 200,
body: message,
};
} catch (error) {
console.log(error);
}
};