forked from sagidM/s3-resizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·90 lines (77 loc) · 2.52 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict'
const AWS = require('aws-sdk');
const S3 = new AWS.S3({signatureVersion: 'v4'});
const Sharp = require('sharp');
const PathPattern = /(.*\/)?(.*)\/(.*)/;
// parameters
const {BUCKET, URL, WHITELIST} = process.env;
exports.handler = async (event) => {
const path = event.queryStringParameters.path;
const parts = PathPattern.exec(path);
const dir = parts[1] || '';
const sizeOption = parts[2];
const options = parts[2].split('_');
const filename = parts[3];
const sizes = options[0].split("x");
const action = options.length > 1 ? options[1] : null;
// Whitelist validation.
if (WHITELIST) {
const whitelistArr = WHITELIST.split(' ');
if (!whitelistArr.includes(sizeOption)) {
return {
statusCode: 400,
body: `Unknown size parameter "${sizeOption}"`,
headers: {"Content-Type": "text/plain"}
};
}
}
// Action validation.
if (action && action !== 'max' && action !== 'min') {
return {
statusCode: 400,
body: `Unknown func parameter "${action}"\n` +
'For query ".../150x150_func", "_func" must be either empty, "_min" or "_max"',
headers: {"Content-Type": "text/plain"}
};
}
try {
const data = await S3
.getObject({Bucket: BUCKET, Key: dir + filename})
.promise();
const width = sizes[0] === 'AUTO' ? null : parseInt(sizes[0]);
const height = sizes[1] === 'AUTO' ? null : parseInt(sizes[1]);
let fit;
switch (action) {
case 'max':
fit = 'inside';
break;
case 'min':
fit = 'outside';
break;
default:
fit = 'cover';
break;
}
const result = await Sharp(data.Body, {failOnError: false})
.resize(width, height, {withoutEnlargement: true, fit})
.rotate()
.toBuffer();
await S3.putObject({
Body: result,
Bucket: BUCKET,
ContentType: data.ContentType,
Key: path,
CacheControl: 'public, max-age=86400'
}).promise();
return {
statusCode: 301,
headers: {"Location" : `${URL}/${path}`}
};
} catch (e) {
return {
statusCode: e.statusCode || 400,
body: 'Exception: ' + e.message,
headers: {"Content-Type": "text/plain"}
};
}
}