-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
80 lines (71 loc) · 1.93 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
const config = require('config')
const files = require('serve-static')
const path = require('path')
const cache = require('http-cache-middleware')
const morgan = require('morgan')
const middlewares = require('./middlewares')
module.exports = () => {
// configuration
const {
DIST_DIRECTORY,
PORT,
CACHE_ENABLED,
CACHE_CONTROL_HEADER_VALUE,
DEFAULT_FILE,
LOGS_FORMAT,
LOGS_ENABLED
} = process.env
const distDirectory = DIST_DIRECTORY || config.get('distDirectory') ||
'dist/'
const port = PORT || config.get('port') ||
3000
const cacheEnabled = isEnabled(CACHE_ENABLED, 'cacheEnabled', config)
const cacheControlHeaderValue = CACHE_CONTROL_HEADER_VALUE || config.get('cacheControlHeaderValue') ||
'public, no-cache, max-age=604800'
const defaultFile = DEFAULT_FILE || config.get('defaultFile') ||
'index.html'
const logsEnabled = isEnabled(LOGS_ENABLED, 'logsEnabled', config)
const logsFormat = LOGS_FORMAT || config.get('logsFormat') ||
'tiny'
// middleware for serving static files
const serve = files(path.join(__dirname, distDirectory), {
lastModified: false,
setHeaders: (res) => {
if (cacheEnabled) {
res.setHeader('cache-control', cacheControlHeaderValue)
}
}
})
// server bootstrap
const server = require('restana')({})
if (logsEnabled) {
server.use(morgan(logsFormat))
}
server.use((req, res, next) => {
if (req.url === '/') {
req.url = defaultFile
}
return next()
})
// supporting custom middlewares
for (const middleware of middlewares) {
server.use(middleware())
}
// supporting cache
if (cacheEnabled) {
server.use(cache())
}
server.use(serve)
return {
server,
port
}
}
function isEnabled (env, configKey, config) {
if (env !== undefined) {
if (env === 'true') return true
else return false
} else {
return config.has(configKey) ? config.get(configKey) : true
}
}