-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
68 lines (52 loc) · 1.57 KB
/
handler.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
"use strict";
const AWS = require('aws-sdk');
const sharp = require('sharp');
//AWS S3 Client
const s3 = new AWS.S3();
module.exports.processFile = async (event, context) => {
const s3MetaData = event.Records[0].s3;
const bucketName = s3MetaData.bucket.name;
const processed = 'processed'
const fileKey = s3MetaData.object.key;
console.log(
`S3 Metadata bucketname : ${bucketName} and uploaded file key : ${fileKey}`
);
try {
const params = {
Bucket: bucketName,
Key: fileKey
};
console.log(`Original params ${JSON.stringify(params)}`);
var origimage = await s3.getObject(params).promise();
} catch (error) {
console.log(error);
return;
}
// set thumbnail width. Resize will set the height automatically to maintain aspect ratio.
const width = 200;
// Use the sharp module to resize the image and save in a buffer.
try {
var buffer = await sharp(origimage.Body).resize(width).toBuffer();
} catch (error) {
console.log(error);
return;
}
// Upload the thumbnail image to the destination bucket
try {
const destparams = {
Bucket: bucketName,
Key: `${processed}/${fileKey.split("/").pop()}`,
Body: buffer,
ContentType: "image"
};
console.log(`Destination params ${JSON.stringify(destparams)}`);
const putResult = await s3.putObject(destparams).promise();
} catch (error) {
console.log(error);
return;
}
console.log(`File conversion done ${bucketName} / ${fileKey} ${JSON.stringify(putResult)}`);
return {
statusCode: 200
};
};