-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
283 lines (252 loc) · 7.94 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Node.js core dependencies
const path = require('path')
// Npm dependencies
const express = require('express')
const session = require('express-session')
const favicon = require('serve-favicon')
const bodyParser = require('body-parser')
const logger = require('./app/logger')
const loggingMiddleware = require('morgan')
const argv = require('minimist')(process.argv.slice(2))
const staticify = require('staticify')(path.join(__dirname, 'public'))
const compression = require('compression')
const nunjucks = require('nunjucks')
const MemoryStore = require('memorystore')(session)
// Local dependencies
const router = require('./app/router')
const paths = require('./app/paths')
const noCache = require('./common/utils/no-cache')
const correlationHeader = require('./common/middleware/correlation-header')
const handle404 = require('./common/middleware/handle-404')
const handle500 = require('./common/middleware/handle-500')
const sessionData = require('./common/utils/session-data')
// Global constants
const unconfiguredApp = express()
const oneYear = 86400000 * 365
const publicCaching = { maxAge: oneYear }
const PORT = process.env.PORT || 3000
const { NODE_ENV } = process.env
const CSS_PATH = staticify.getVersionedPath('/stylesheets/application.min.css')
const JAVASCRIPT_PATH = staticify.getVersionedPath(
'/javascripts/application.js'
)
const { SERVICE_NAME, MINIMUM_PAY_THRESHOLD } = require('./app/constants')
// Define app views
const APP_VIEWS = [
path.join(__dirname, 'node_modules/govuk-frontend/dist/govuk/'),
path.join(__dirname, 'node_modules/govuk-frontend/dist/govuk/components/'),
path.join(__dirname, 'app/views/'),
path.join(__dirname, 'common/macros/')
]
const cookieParser = require('cookie-parser')
function initialiseGlobalMiddleware (app) {
app.set('settings', { getVersionedPath: staticify.getVersionedPath })
app.use(
favicon(
path.join(
__dirname,
'node_modules/govuk-frontend/dist/govuk/assets/',
'images',
'favicon.ico'
)
)
)
app.use(compression())
app.use(staticify.middleware)
if (process.env.DISABLE_REQUEST_LOGGING !== 'true') {
app.use(
/\/((?!images|public|stylesheets|javascripts).)*/,
loggingMiddleware(
':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" - total time :response-time ms'
)
)
}
app.use(cookieParser())
app.use((req, res, next) => {
res.locals.asset_path = '/public/' // eslint-disable-line camelcase
const cmUserPreferences = req.cookies['cm-user-preferences']
if (cmUserPreferences) {
res.locals.cmUserPreferences = JSON.parse(cmUserPreferences)
}
noCache(res)
next()
})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use('*', correlationHeader)
const maxAge = 86400000 // Prune expired entries every 24 hours.
app.use(
session({
secret: 'beis-spl-eligibility-tool',
name: 'application',
store: new MemoryStore({
checkPeriod: maxAge
}),
resave: false,
saveUninitialized: false
})
)
app.use(sessionData)
function handleFormErrorsForView (app) {
app
.route('*')
.post(function initializeSessionErrors (req, res, next) {
req.session.errors = {}
next()
})
.get(function addErrorsToLocals (req, res, next) {
res.locals.errors = req.session.errors
next()
})
}
handleFormErrorsForView(app)
app.get('*', require('./common/middleware/step-validation'))
}
function initialiseProxy (app) {
app.enable('trust proxy')
}
function initialiseTemplateEngine (app) {
// Configure nunjucks
// see https://mozilla.github.io/nunjucks/api.html#configure
const nunjucksConfiguration = {
express: app, // The express app that nunjucks should install to
autoescape: true, // Controls if output with dangerous characters are escaped automatically
throwOnUndefined: false, // Throw errors when outputting a null/undefined value
trimBlocks: true, // Automatically remove trailing newlines from a block/tag
lstripBlocks: true, // Automatically remove leading whitespace from a block/tag
watch: NODE_ENV !== 'production', // Reload templates when they are changed (server-side). To use watch, make sure optional dependency chokidar is installed
noCache: NODE_ENV !== 'production' // Never use a cache and recompile templates each time (server-side)
}
// Initialise nunjucks environment
const nunjucksEnvironment = nunjucks.configure(
APP_VIEWS,
nunjucksConfiguration
)
// Set view engine
app.set('view engine', 'njk')
// Version static assets on production for better caching
// if it's not production we want to re-evaluate the assets on each file change
nunjucksEnvironment.addGlobal(
'css_path',
NODE_ENV === 'production'
? CSS_PATH
: staticify.getVersionedPath('/stylesheets/application.min.css')
)
nunjucksEnvironment.addGlobal(
'js_path',
NODE_ENV === 'production'
? JAVASCRIPT_PATH
: staticify.getVersionedPath('/javascripts/application.js')
)
nunjucksEnvironment.addGlobal('service_name', SERVICE_NAME)
nunjucksEnvironment.addGlobal('minimum_pay_threshold', MINIMUM_PAY_THRESHOLD)
// Paths to external resources and tools.
nunjucksEnvironment.addGlobal(
'mainstream_guidance_root_path',
process.env.MAINSTREAM_GUIDANCE_ROOT_PATH ||
'https://www.gov.uk/shared-parental-leave-and-pay'
)
nunjucksEnvironment.addGlobal(
'planner_root_path',
process.env.PLANNER_ROOT_PATH ||
'https://plan-shared-parental-leave.service.gov.uk'
)
nunjucksEnvironment.addGlobal(
'employment_status_root_path',
process.env.EMPLOYMENT_STATUS_ROOT_PATH ||
'https://www.gov.uk/employment-status'
)
nunjucksEnvironment.addGlobal(
'GOOGLE_ANALYTICS_ID',
process.env.GOOGLE_ANALYTICS_ID
)
// Add filters
const commonFilters = require('./common/spl-common-filters')(
nunjucksEnvironment
)
Object.entries(commonFilters).forEach((nameAndFunction) =>
nunjucksEnvironment.addFilter(...nameAndFunction)
)
// App filters must be imported after common filters have been added so that common filters are available for use in app filters
const appFilters = require('./app/filters')(nunjucksEnvironment)
Object.entries(appFilters).forEach((nameAndFunction) =>
nunjucksEnvironment.addFilter(...nameAndFunction)
)
}
function initialisePublic (app) {
app.use(
'/javascripts',
express.static(
path.join(__dirname, '/public/assets/javascripts'),
publicCaching
)
)
app.use(
'/images',
express.static(path.join(__dirname, '/public/images'), publicCaching)
)
app.use(
'/stylesheets',
express.static(
path.join(__dirname, '/public/assets/stylesheets'),
publicCaching
)
)
app.use('/public', express.static(path.join(__dirname, '/public')))
app.use(
'/',
express.static(path.join(__dirname, '/node_modules/govuk-frontend/dist/govuk/'))
)
}
function initialiseRoutes (app) {
const routes = paths.getAllPaths()
app.locals.paths = routes
app.use('/', router)
}
function handleErrors (app) {
app.use(handle404)
if (process.env.NODE_ENV !== 'development') {
app.use(handle500)
}
}
function listen () {
const app = initialise()
app.listen(PORT, () => {
logger.info(`App listening on port ${PORT}`, {
eventType: 'ApplicationEvent'
})
})
}
/**
* Configures app
* @return app
*/
function initialise () {
const app = unconfiguredApp
app.disable('x-powered-by')
initialiseProxy(app)
initialiseGlobalMiddleware(app)
initialiseTemplateEngine(app)
initialisePublic(app)
initialiseRoutes(app)
handleErrors(app)
return app
}
/**
* Starts app after ensuring DB is up
*/
function start () {
listen()
}
/**
* -i flag. Immediately invoke start.
* Allows script to be run by task runner
*/
if (argv.i) {
start()
}
module.exports = {
start,
getApp: initialise,
staticify
}