This repository was archived by the owner on Jun 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
88 lines (77 loc) · 2.32 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
const express = require("express");
const { getScreenshot } = require("./server/chromium");
const { dayInSecs } = require("./utils/time");
const packageJSON = require("./package.json");
const v1 = {
parseRequest: require("./server/v1/parser"),
getHTML: require("./server/v1/template"),
};
const v2 = {
parseRequest: require("./server/v2/parser"),
getHTML: require("./server/v2/template"),
};
const app = express();
const port = process.env.PORT || 3000;
const browserOpts = {
remoteBrowser: process.env.REMOTE_BROWSER,
containerizedBrowser: process.env.CONTAINERIZED_BROWSER,
};
const isHTMLDebug = process.env.HTML_DEBUG === "1";
const cacheAge = 7 * dayInSecs;
const renderScreenshot = (res, screenshot, fileType) => {
res.statusCode = 200;
res.setHeader("Content-Type", `image/${fileType}`);
res.setHeader(
"Cache-Control",
`public, immutable, no-transform, s-maxage=${cacheAge}, max-age=${cacheAge}`
);
res.end(screenshot);
};
const renderError = (res, err) => {
res.statusCode = 500;
res.setHeader("Content-Type", "text/html");
res.end("<h1>Internal Error</h1><p>Sorry, there was a problem.</p>");
console.error(err);
};
const handler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch((err) => renderError(res, err));
app.get(
"/api/v1/:slug",
handler(async (req, res) => {
const props = v1.parseRequest(req);
const html = v1.getHTML(props, isHTMLDebug);
if (isHTMLDebug) {
res.setHeader("Content-Type", "text/html");
res.end(html);
return;
}
const { fileType } = props;
const screenshot = await getScreenshot(html, fileType, browserOpts);
renderScreenshot(res, screenshot, fileType);
})
);
app.get(
"/api/v2/:slug",
handler(async (req, res) => {
const props = v2.parseRequest(req);
const html = v2.getHTML(props, isHTMLDebug);
if (isHTMLDebug) {
res.setHeader("Content-Type", "text/html");
res.end(html);
return;
}
const { fileType } = props;
const screenshot = await getScreenshot(html, fileType, {
...browserOpts,
width: props.width,
height: props.height,
});
renderScreenshot(res, screenshot, fileType);
})
);
app.get("*", (_, res) => {
res.redirect(packageJSON.repository);
});
app.listen(port, () => {
console.log(`started server, listening at ${port}.`);
});