-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
84 lines (66 loc) · 2.73 KB
/
main.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
/* **************************************
CanIUse Embed Screenshot
************************************** */
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const takeScreenshot = require("./modules/take-screenshot");
const trimScreenshot = require("./modules/trim-screenshot");
const uploadScreenshot = require("./modules/upload-screenshot");
const getFeatureList = require("./modules/get-feature-list");
const getMDNBrowserCompatData = require("./modules/get-mdn-browser-compat-data");
const allowedOrigins = process.env.ALLOWED_ORIGINS;
console.log("Allowed origins: ", process.env.ALLOWED_ORIGINS);
app.set('port', (process.env.PORT || 3000));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get("/", (req, res) => {
res.status(200).send("Welcome to the CanIUse Embed API!");
});
app.post("/capture", async (req, res) => {
const requestOrigin = req.get('origin');
console.log("Request from:", requestOrigin);
if (allowedOrigins && !allowedOrigins.includes(requestOrigin)) return res.status("400").json({body: "Unauthorized host"});
if (!req.body) return res.status("400").send("Need request params");
if (!req.body.feature) return res.status("400").send("Feature required");
const feature = req.body.feature;
const periods = req.body.periods;
const accessibleColours = req.body.accessibleColours === "true";
console.log(feature);
console.log(periods);
console.log(accessibleColours);
try {
let screenshot = await takeScreenshot(feature, periods, accessibleColours);
screenshot = await trimScreenshot(screenshot);
screenshot = await uploadScreenshot(feature, screenshot, {
folder: 'caniuse-embed/static',
public_id: `${feature}-${new Date().getTime()}`
});
res.status(200).json(screenshot);
} catch (err) {
console.error(err);
res.status("500").json(err);
}
});
app.get("/features", async (req, res) => {
const features = await getFeatureList();
res.status(200).json(features);
});
app.post("/mdn-browser-compat-data", async (req, res) => {
try {
const feature = req && req.body && req.body.feature;
const data = await getMDNBrowserCompatData(feature);
res.status(200).json(data);
} catch (err) {
console.error(err);
res.status("500").json(err);
}
});
const server = app.listen(app.get('port'), function () {
console.log("app running on port.", server.address().port);
});