-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
43 lines (40 loc) · 1.69 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
const Sharp = require('sharp');
const Path = require('path');
const ImageFetcher = require('./src/image-fetcher');
const ImageProcessor = require('./src/image-processor');
module.exports.processImage = (event, context, callback) => {
const bucket = decodeURIComponent(event.pathParameters.bucket);
const imageFetcher = new ImageFetcher(bucket);
const imageProcessor = new ImageProcessor(Sharp);
const file = decodeURIComponent(event.pathParameters.file);
const quality = event.queryStringParameters && +event.queryStringParameters.quality || 100;
const size = {
width: event.queryStringParameters && +event.queryStringParameters.width || null,
height: event.queryStringParameters && +event.queryStringParameters.height || null,
};
const blur = event.queryStringParameters && +event.queryStringParameters.blur || false;
const webp = event.queryStringParameters && event.queryStringParameters.webp || false;
return imageFetcher
.fetchImage(file)
.then(data => imageProcessor.resize(data.image, size, quality))
.then(data => blur ? imageProcessor.blur(data.image, blur) : data)
.then(data => webp ? imageProcessor.webp(data.image) : data)
.then(data => {
const contentType = data.contentType;
const img = new Buffer(data.image.buffer, 'base64');
const fileName = Path.parse(file).base;
callback(null, {
statusCode: 200,
headers: {
'Content-Type': contentType,
'Content-Disposition': 'inline; filename="' + fileName + '"'
},
body: img.toString('base64'),
isBase64Encoded: true,
});
})
.catch(error => {
console.error('Error:', error);
callback(null, error);
});
};