-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
102 lines (91 loc) · 2.75 KB
/
app.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
91
92
93
94
95
96
97
98
99
100
101
102
const express = require("express");
const bodyParser = require("body-parser");
const {
QRCodeStyling
} = require("qr-code-styling-node/lib/qr-code-styling.common.js");
const nodeCanvas = require("canvas");
const {
JSDOM
} = require("jsdom");
// Initialize the express app
const app = express();
// Operation port
const PORT = process.env.PORT || 3000;
// Select view engine
// For this project we use EJS
app.use(express.static(__dirname + "/"));
app.set("view engine", "ejs");
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(bodyParser.json());
// Render homepage
app.get("/", async (req, res) => {
res.render("index");
});
// One function to generate the QR codes
app.post("/generate", async (req, res) => {
// Parse the json from the request body
const modsObject = JSON.parse(req.body.modsJSON);
// QR options sent from frontend
const options = {
width: parseInt(modsObject.width),
height: parseInt(modsObject.height),
margin: parseInt(modsObject.margin),
data: req.body.data,
image: req.body.logoSrc,
dotsOptions: {
type: modsObject.dotsOptionsType,
color: modsObject.dotsOptionsSingleColor,
gradient: modsObject.dotsOptionsGradient
},
cornersSquareOptions: {
type: modsObject.cornersSquareOptionsType,
color: modsObject.cornersSquareOptionsSingleColor,
gradient: modsObject.cornersSquareOptionsGradient
},
cornersDotOptions: {
type: modsObject.cornersDotOptionsType,
color: modsObject.cornersDotOptionsSingleColor,
gradient: modsObject.cornersDotOptionsGradient
},
backgroundOptions: {
color: modsObject.backgroundOptionsSingleColor,
gradient: modsObject.backgroundOptionsGradient
},
imageOptions: {
hideBackgroundDots: modsObject.imageOptionsHideBackgroundDots,
imageSize: modsObject.imageOptionsImageSize,
margin: modsObject.imageOptionsMargin,
crossOrigin: "anonymous"
},
qrOptions: {
typeNumber: modsObject.qrOptionsTypeNumber,
mode: modsObject.qrOptionsMode,
errorCorrectionLevel: modsObject.qrOptionsErrorCorrectionLevel
},
}
// Generate the QR Code
const qrCodeImage = new QRCodeStyling({
nodeCanvas,
...options
});
// Get QR Code raw data and send it back to frontend
qrCodeImage.getRawData("png").then((buffer) => {
const bufferToB64 = Buffer.from(buffer).toString("base64");
const base64 = "data:image/png;base64," + bufferToB64;
res.send(base64);
});
});
// 404 redirects to home page
// I don't think a separate 404 page is required at the moment
// Maybe in the future?
app.get("*", async (req, res) => {
// Render homepage
res.render("index");
});
app.listen(PORT, () => {
console.log(`Running on port ${PORT}`);
});