-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
59 lines (47 loc) · 1.24 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
// `npm start` runs this script.
import readEnvironment from './environment.js'
import requestHandler from './index.js'
import http from 'http'
import pino from 'pino'
import pinoHTTP from 'pino-http'
import toobusy from 'toobusy-js'
// Logging
const logger = pino()
const addLoggers = pinoHTTP({ logger })
// Environment
const environment = readEnvironment()
if (environment.missing.length !== 0) {
environment.missing.forEach(missing => {
logger.error({ variable: missing }, 'missing environment variable')
})
process.exit(1)
}
// Error Handling
process
.on('SIGTERM', shutdown)
.on('SIGQUIT', shutdown)
.on('SIGINT', shutdown)
.on('uncaughtException', (error) => {
logger.error(error, 'uncaughtException')
shutdown()
})
// HTTP Server
const server = http.createServer()
server.on('request', (request, response) => {
try {
addLoggers(request, response)
if (toobusy()) {
response.statusCode = 503
response.end('Server Too Busy')
}
requestHandler(request, response)
} catch (error) {
request.log.error(error)
}
})
server.listen(process.env.PORT || 8080, () => {
logger.info({ port: server.address().port }, 'listening')
})
function shutdown () {
server.close(() => process.exit())
}