-
Notifications
You must be signed in to change notification settings - Fork 228
/
index.jsx
187 lines (163 loc) · 4.84 KB
/
index.jsx
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
import express from 'express';
import compression from 'compression';
import expressStaticGzip from 'express-static-gzip';
import path from 'path';
// not part of react-helmet
import helmet from 'helmet';
import gnuTP from 'gnu-terry-pratchett';
import routes from '../app/routes';
import {
articleDataRegexPath,
articleManifestRegexPath,
articleSwRegexPath,
frontpageDataRegexPath,
frontpageManifestRegexPath,
frontpageSwRegexPath,
mediaDataRegexPath,
} from '../app/routes/regex';
import nodeLogger from '../app/lib/logger.node';
import renderDocument from './Document';
import getRouteProps from '../app/routes/getInitialData/utils/getRouteProps';
import logResponseTime from './utilities/logResponseTime';
const morgan = require('morgan');
const logger = nodeLogger(__filename);
const publicDirectory = 'build/public';
logger.debug(
`Application outputting logs to directory "${process.env.LOG_DIR}"`,
);
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["write"] }] */
class LoggerStream {
write(message) {
logger.info(message.substring(0, message.lastIndexOf('\n')));
}
}
const constructDataFilePath = (pageType, service, id) => {
const dataPath = pageType === 'frontpage' ? 'index.json' : `${id}.json`;
return path.join(process.cwd(), 'data', service, pageType, dataPath);
};
const server = express();
/*
* Default headers, compression, logging, status route
*/
server
.disable('x-powered-by')
.use(
morgan('tiny', {
skip: (req, res) => res.statusCode === 200,
stream: new LoggerStream(),
}),
)
.use(compression())
.use(helmet({ frameguard: { action: 'deny' } }))
.use(gnuTP())
.get('/status', (req, res) => {
res.sendStatus(200);
});
/*
* Prod only logging - response time
*/
if (process.env.APP_ENV !== 'local') {
server.use(logResponseTime);
}
/*
* Local env routes - fixture data
*/
const sendDataFile = (res, dataFilePath, next) => {
res.sendFile(dataFilePath, {}, sendErr => {
if (sendErr) {
logger.error(sendErr);
next(sendErr);
}
});
};
if (process.env.APP_ENV === 'local') {
server
.use((req, res, next) => {
if (req.url.substr(-1) === '/' && req.url.length > 1)
res.redirect(301, req.url.slice(0, -1));
else next();
})
.use(
expressStaticGzip(publicDirectory, {
enableBrotli: true,
orderPreference: ['br'],
redirect: false,
}),
)
.get(articleDataRegexPath, async ({ params }, res, next) => {
const { service, id } = params;
const dataFilePath = constructDataFilePath('articles', service, id);
sendDataFile(res, dataFilePath, next);
})
.get(frontpageDataRegexPath, async ({ params }, res, next) => {
const { service } = params;
const dataFilePath = constructDataFilePath('frontpage', service);
sendDataFile(res, dataFilePath, next);
})
.get(mediaDataRegexPath, async ({ params }, res, next) => {
const { service, serviceId, mediaId } = params;
const dataFilePath = path.join(
process.cwd(),
'data',
service,
serviceId,
mediaId,
);
sendDataFile(res, `${dataFilePath}.json`, next);
})
.get('/ckns_policy/*', (req, res) => {
// Route to allow the cookie banner to make the cookie oven request
// without throwing an error due to not being on a bbc domain.
res.sendStatus(200);
});
}
/*
* Application env routes
*/
server
.get([articleSwRegexPath, frontpageSwRegexPath], (req, res) => {
const swPath = `${__dirname}/public/sw.js`;
res.sendFile(swPath, {}, error => {
if (error) {
logger.error(error);
res.status(500).send('Unable to find service worker.');
}
});
})
.get(
[articleManifestRegexPath, frontpageManifestRegexPath],
async ({ params }, res) => {
const { service } = params;
const manifestPath = `${__dirname}/public/${service}/manifest.json`;
res.sendFile(manifestPath, {}, error => {
if (error) {
console.log(error); // eslint-disable-line no-console
res.status(500).send('Unable to find manifest.');
}
});
},
)
.get('/*', async ({ url, headers, path: urlPath }, res) => {
try {
const { service, isAmp, route, match } = getRouteProps(routes, url);
const data = await route.getInitialData(match.params);
const { status } = data;
const bbcOrigin = headers['bbc-origin'];
data.path = urlPath;
res.status(status).send(
await renderDocument({
bbcOrigin,
data,
isAmp,
routes,
service,
url,
}),
);
} catch ({ message, status }) {
// Return an internal server error for any uncaught errors
logger.error(`status: ${status || 500} - ${message}`);
res.status(500).send(message);
}
});
export default server;