-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (72 loc) · 2.17 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
const fs = require("fs"),
request = require("request");
const sharp = require("sharp");
exports.handler = async (event) => {
const query = event["queryStringParameters"];
const download = function (uri, filename, callback) {
return new Promise((resolve, _reject) => {
request.head(uri, function (_err, _res, _body) {
request(uri)
.pipe(fs.createWriteStream(filename))
.on("close", () => {
resolve();
});
});
});
};
const { file } = query;
const imageExtension = /[a-z0-9A-Z]+\.([a-z]+)$/.exec(file)[1];
const originalImage = file.replace(imageExtension, "png");
const imageUrl = `${process.env.FILE_HOST}/images/${originalImage}`;
const pieces = originalImage.split("/");
const tmpPath = `/tmp/${pieces[pieces.length - 1]}`;
await download(imageUrl, tmpPath);
const response = await responseFromPath(tmpPath, query);
return response;
};
function responseFromPath(path, query) {
const { file } = query;
const imageExtension = /[a-z0-9A-Z]+\.([a-z]+)$/.exec(file)[1];
let { width } = query;
return new Promise((resolve, _reject) => {
sharp(path)
.metadata()
.then((info) => {
width = width ? parseInt(width) : info.width;
let buffer, content_type;
if (imageExtension === "webp") {
buffer = resizeAndWebp(path, width);
content_type = "image/webp";
} else {
buffer = resize(path, width);
content_type = `image/png`;
}
buffer.then((data) => {
const response = {
statusCode: 200,
headers: {
"content-type": content_type,
"cache-control": "max-age=31536000, public",
},
body: data.toString("base64"),
isBase64Encoded: true,
};
resolve(response);
});
});
});
}
function resizeAndWebp(file, width) {
const sharp = require("sharp");
return sharp(file)
.resize({ width })
.webp({
quality: 100,
reductionEffort: 6,
})
.toBuffer();
}
function resize(file, width) {
const sharp = require("sharp");
return sharp(file).resize({ width }).toBuffer();
}