-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver-helpers.mjs
46 lines (42 loc) · 1.17 KB
/
server-helpers.mjs
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
/* eslint-disable-next-line */
function errorHandler(err, req, res, next) {
if (res.headersSent) {
return next(err);
}
if (err.message.startsWith('template not found')) {
return res.status(404).render('404.html', {});
}
res.status(500).send({errors: `${err}`});
}
/* eslint-disable-next-line */
function enableCors(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
next();
}
/* eslint-disable-next-line */
function forceSSL(req, res, next) {
const fromCron = req.get('X-Appengine-Cron');
if (!fromCron && req.hostname !== 'localhost' && req.get('X-Forwarded-Proto') === 'http') {
return res.redirect(`https://${req.hostname}${req.url}`);
}
next();
}
/* eslint-disable-next-line */
function addRequestHelpers(req, res, next) {
req.getCurrentUrl = () => `${req.protocol}://${req.get('host')}${req.originalUrl}`;
req.getOrigin = () => {
let protocol = 'https';
if (req.hostname === 'localhost') {
protocol = 'http';
}
return `${protocol}://${req.get('host')}`;
};
next();
}
export default {
enableCors,
forceSSL,
errorHandler,
addRequestHelpers,
};