forked from amazon-archives/serverless-image-resizing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
36 lines (33 loc) · 925 Bytes
/
index.js
File metadata and controls
36 lines (33 loc) · 925 Bytes
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
var AWS = require('aws-sdk');
var S3 = new AWS.S3();
var Sharp = require('sharp');
var BUCKET = process.env.BUCKET;
var URL = process.env.URL;
exports.handler = function(event, context) {
var key = event.queryStringParameters.key;
var match = key.match(/(\d+)x(\d+)\/(.*)/);
var width = parseInt(match[1], 10);
var height = parseInt(match[2], 10);
var originalKey = match[3];
S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then((data) => Sharp(data.Body)
.resize(width, height)
.max()
.toFormat('png')
.toBuffer()
)
.then((buffer) => S3.putObject({
Body: buffer,
Bucket: BUCKET,
ContentType: 'image/png',
Key: key
}).promise()
)
.then(() => context.succeed({
statusCode: '301',
headers: {'location': `${URL}/${key}`},
body: ''
})
)
.catch((err) => context.fail(err))
}