-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapp.js
More file actions
269 lines (227 loc) · 7.46 KB
/
app.js
File metadata and controls
269 lines (227 loc) · 7.46 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
const express = require("express");
const compression = require("compression");
const nunjucks = require("nunjucks");
const bodyParser = require("body-parser");
const path = require("path");
const appRoutes = require("./app/routes.js");
const dateFilter = require("nunjucks-date-filter");
const markdown = require("nunjucks-markdown");
const marked = require("marked");
const govukMarkdown = require("govuk-markdown");
const Airtable = require("airtable");
const app = express();
const base = new Airtable({ apiKey: process.env.airtableFeedbackKey }).base(
process.env.airtableFeedbackBase
);
// Set up views and nunjucks environment
var nunjuckEnv = nunjucks.configure(
[
"app/views",
"app/views/layouts",
"node_modules/govuk-frontend/dist/",
"node_modules/dfe-frontend/packages/components",
], {
autoescape: true,
express: app,
watch: false,
extension: "html",
noCache: false,
}
);
app.use(compression());
// Serve static files
app.use(
"/govuk",
express.static(
path.join(__dirname, "node_modules/govuk-frontend/govuk/assets")
)
);
app.use(
"/dfe",
express.static(path.join(__dirname, "node_modules/dfe-frontend/dist"))
);
app.use("/assets", express.static("app/public"));
app.use("/public", express.static("app/public"));
app.use(express.json());
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({ extended: true }));
app.use(
"/favicon.ico",
express.static(path.join(__dirname, "public/assets/images/favicon.ico"))
);
nunjuckEnv.addFilter("date", dateFilter);
marked.use(
govukMarkdown({
headingsStartWith: "xl",
})
);
markdown.register(nunjuckEnv, marked.parse);
// Set view engine to Nunjucks with .html extension
app.set("view engine", "html");
// Add a route that serves the app/robots.txt file
app.get("/robots.txt", function(req, res) {
res.sendFile(path.join(__dirname, "app/robots.txt"));
});
// 301 Redirects
app.get("/design-ops*", (req, res) => {
res.redirect(301, "/designops");
});
// Define specific subsystems that should be redirected
const archivedRedirects = {
"rsd-design-system": "https://webarchive.nationalarchives.gov.uk/ukgwa/20241206052023/https://design.education.gov.uk/design-system/rsd-design-system",
"ncs-design-system": "https://webarchive.nationalarchives.gov.uk/ukgwa/20241206052208/https://design.education.gov.uk/design-system/ncs-design-system",
};
app.get("/design-system/:subsystem*", function(req, res, next) {
const { subsystem } = req.params;
if (archivedRedirects[subsystem]) {
res.redirect(301, archivedRedirects[subsystem]);
} else {
next();
}
});
app.get("/learn/how-many-users", function(req, res, next) {
res.redirect(
301,
"https://accessibility.education.gov.uk/app/how-many-people"
);
});
app.get("/learn/how-many-users/:count", function(req, res, next) {
res.redirect(
301,
"https://accessibility.education.gov.uk/app/how-many-people/" +
req.params.count
);
});
const { buildSearchIndex, search } = require("./middleware/search.js");
buildSearchIndex("http://design.education.gov.uk/sitemap.xml")
.then(() => console.log("Search index ready"))
.catch((err) => console.error("Error initialising search:", err));
app.post("/form-response/feedback", (req, res) => {
const { response } = req.body;
// Prevent bots submitting empty feedback
if (!response || response.trim() === "") {
return res
.status(400)
.json({ success: false, message: "No feedback provided" });
}
// Prevent long feedback
if (response.length > 400) {
return res
.status(400)
.json({ success: false, message: "Feedback too long" });
}
console.log("Feedback received:", response);
const service = "Design manual"; // Example service name
const pageURL = req.headers.referer || "Unknown"; // Capture the referrer URL
base("Feedback").create(
[{
fields: {
Feedback: response,
Service: service,
URL: pageURL,
},
}, ],
function(err, records) {
if (err) {
console.error("Airtable Error:", err);
return res
.status(500)
.json({ success: false, message: "Could not send feedback" });
}
res.json({ success: true, message: "Thank you for your feedback" });
}
);
});
// e.g. add a /search route:
app.get("/search", (req, res) => {
const query = req.query.q || "";
let data = [];
if (!query.trim()) {
return res.render("search/index", { data });
}
const results = search(query);
// Just pass the results to the template
return res.render("search/index", { data: results, query });
});
// Use application routes
app.use("/", appRoutes);
// Clean URLs
app.get(/\.html?$/i, function(req, res) {
let urlPath = req.path;
const parts = urlPath.split(".");
parts.pop();
urlPath = parts.join(".");
res.redirect(urlPath);
});
// Dynamic Route Matching for URLs without extensions
app.get(/^([^.]+)$/, function(req, res, next) {
matchRoutes(req, res, next);
});
// Render sitemap.xml in XML format
app.get("/sitemap.xml", (_, res) => {
res.set({ "Content-Type": "application/xml" });
res.render("sitemap.xml");
});
// Route matching function
function matchRoutes(req, res, next) {
let path = req.path;
// Remove the first slash, render won't work with it
path = path.startsWith("/") ? path.slice(1) : path;
// If it's blank, render the root index
if (path === "") {
path = "index";
}
console.log(path);
renderPath(path, res, next);
}
function renderPath(path, res, next) {
// Try to render the path
res.render(path, function(error, html) {
if (!error) {
// Success - send the response
res.set({ "Content-type": "text/html; charset=utf-8" });
res.end(html);
return;
}
if (!error.message.startsWith("template not found")) {
// We got an error other than template not found - call next with the error
next(error);
return;
}
if (!path.endsWith("/index")) {
// Maybe it's a folder - try to render [path]/index.html
renderPath(path + "/index", res, next);
return;
}
// We got template not found both times - call next to trigger the 404 page
next();
});
}
// Also handle .html files directly
function renderPathWithExtension(path, res, next) {
// Try to render the path with .html extension
res.render(path + ".html", function(error, html) {
if (!error) {
// Success - send the response
res.set({ "Content-type": "text/html; charset=utf-8" });
res.end(html);
return;
}
if (!error.message.startsWith("template not found")) {
// We got an error other than template not found - call next with the error
next(error);
return;
}
// Try without .html extension
renderPath(path, res, next);
});
}
// Handle 404 errors
app.use(function(req, res, next) {
res.status(404).render("404.html");
});
// Start the server
const PORT = process.env.PORT || 3066;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});