forked from veteransaffairscanada/vac-benefits-directory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
189 lines (170 loc) · 5.86 KB
/
server.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const express = require("express");
const bodyParser = require("body-parser");
const next = require("next");
const Cookies = require("universal-cookie");
const helmet = require("helmet");
const compression = require("compression");
const fs = require("fs");
const { parseUserAgent } = require("detect-browser");
const dev = process.env.NODE_ENV !== "production";
const staging = process.env.STAGING !== undefined;
const app = next({ dev });
const handle = app.getRequestHandler();
const deploy = require("./utils/deploy_notification");
const airTable = require("./utils/airtable_es2015");
const { checkURL } = require("./utils/url_check");
const Logger = require("./utils/logger").default;
const readJsonAsync = function(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, (err, buffer) => {
if (err) reject(err);
else resolve(JSON.parse(buffer));
});
});
};
const getAllData = async function() {
let airtableData;
if (staging) {
// eslint-disable-next-line no-console
console.log("Staging environment, downloading from Airtable");
airtableData = await airTable.hydrateFromAirtable();
} else {
// eslint-disable-next-line no-console
console.log("Production environment, using static file");
airtableData = await readJsonAsync("data/data.json");
}
return { airtableData: airtableData };
};
const copyValidTables = (oldData, newData) => {
Object.keys(newData)
.filter(tableName => newData[tableName].length > 0)
.forEach(tableName => {
oldData[tableName] = newData[tableName];
});
oldData.timestamp = newData.timestamp;
};
Promise.resolve(getAllData()).then(allData => {
let data = allData.airtableData;
if (staging) {
setInterval(function() {
Promise.resolve(airTable.hydrateFromAirtable()).then(newData => {
copyValidTables(data, newData);
Logger.info("Cache refreshed automatically @ " + data.timestamp, {
source: "/server.js"
});
});
}, 1000 * 60 * 60);
}
app.prepare().then(() => {
const server = express();
server.use(compression());
server.use(bodyParser.json());
server.use(helmet());
// submitting Feedback
server.post("/submitComment", (req, res) => {
Logger.info("Submitting comments", { source: "/server.js" });
airTable.writeFeedback(req.body);
res.sendStatus(200);
});
// submitting beta Feedback
server.post("/submitBetaFeedback", (req, res) => {
Logger.info("Submitting beta feedback", { source: "/server.js" });
airTable.writeBetaFeedback(req.body);
res.sendStatus(200);
});
// handle URL validation
let urlCache = {};
server.post("/checkURL", (req, res) => {
const benefitId = encodeURIComponent(req.body.id);
Logger.info(`Checking URL for: ${req.body.id}`, {
source: "/server.js"
});
Promise.resolve(checkURL(benefitId, urlCache, data)).then(newUrls => {
urlCache = newUrls;
res.setHeader("Content-Type", "application/json");
res.send(JSON.stringify(urlCache[benefitId]));
});
});
// use next.js
server.get("*", (req, res) => {
// Check if browse is less than IE 11
const ua = req.headers["user-agent"];
const browser = parseUserAgent(ua);
const lang = req.query.lng
? req.query.lng
: req.headers["accept-language"];
req.data = data;
req.language = lang ? lang.split(",")[0] : "en";
if (
browser &&
browser.name === "ie" &&
parseInt(browser.version) < 11 &&
!req.url.includes("all-benefits") &&
!req.url.includes(".css")
) {
res.sendFile("fallback-pages/browser-incompatible.html", {
root: __dirname
});
} else if (req.url.includes("refresh")) {
Logger.info("Refreshing Cache ...", { source: "/server.js" });
let referrer = req.header("Referer") || "/";
urlCache = {};
Promise.resolve(airTable.hydrateFromAirtable()).then(newData => {
copyValidTables(data, newData);
res.redirect(referrer);
Logger.info("Cache refreshed @ " + data.timestamp, {
source: "/server.js"
});
});
} else if (req.url.includes("data-validation") && !staging) {
res
.status(404)
.send("The Data Validation page only exists on the staging app.");
} else if (req.url.includes("favourites") && !staging) {
res
.status(404)
.send("The Favourites page only exists on the staging app.");
} else if (req.url.includes("summary") && !staging) {
res
.status(404)
.send("The summary page only exists on the staging app.");
} else {
const favouriteBenefits = new Cookies(req.headers.cookie).get(
"favouriteBenefits"
);
if (favouriteBenefits) {
const existingBenefitIds = data.benefits.map(x => x.id);
// update cookies to prune any benefits that have been removed from Airtable
const validFavouriteBenefits = favouriteBenefits.filter(
x => existingBenefitIds.indexOf(x) > -1
);
req.data.favouriteBenefits = validFavouriteBenefits;
}
let startTime = new Date();
handle(req, res).then(() => {
let duration = new Date() - startTime;
let url = req.url;
Logger.info(
{
event: "Page render duration in ms",
url: url,
duration: duration
},
{
contentType: "application/json",
source: "/server.js"
}
);
});
}
});
const port = process.env.PORT || 3000;
server.listen(port, err => {
if (err) throw err;
Logger.debug(`> Ready on http://localhost: ${port}`, {
source: "/server.js"
});
deploy.notify();
});
});
});