This repository has been archived by the owner on Apr 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
94 lines (79 loc) · 2.4 KB
/
index.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
'use strict'
const express = require('express')
const httpErrors = require('http-errors')
const pino = require('pino')
const pinoHttp = require('pino-http')
const bodyParser = require('body-parser')
module.exports = function main (options, cb) {
// Set default options
const ready = cb || function () {}
const opts = Object.assign({
// Default options
}, options)
const logger = pino()
// Server state
let server
let serverStarted = false
let serverClosing = false
// Setup error handling
function unhandledError (err) {
// Log the errors
logger.error(err)
// Only clean up once
if (serverClosing) {
return
}
serverClosing = true
// If server has started, close it down
if (serverStarted) {
server.close(function () {
process.exit(1)
})
}
}
process.on('uncaughtException', unhandledError)
process.on('unhandledRejection', unhandledError)
// Create the express app
const app = express()
// Common middleware
// app.use(/* ... */)
app.use(pinoHttp({ logger }))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Register routes
// @NOTE: require here because this ensures that even syntax errors
// or other startup related errors are caught logged and debuggable.
// Alternativly, you could setup external log handling for startup
// errors and handle them outside the node process. I find this is
// better because it works out of the box even in local development.
require('./routes')(app, opts)
// Common error handlers
app.use(function fourOhFourHandler (req, res, next) {
next(httpErrors(404, `Route not found: ${req.url}`))
})
app.use(function fiveHundredHandler (err, req, res, next) {
if (err.status >= 500) {
logger.error(err)
}
res.status(err.status || 500).json({
messages: [{
code: err.code || 'InternalServerError',
message: err.message
}]
})
})
// Start server
server = app.listen(opts.port, opts.host, function (err) {
if (err) {
return ready(err, app, server)
}
// If some other error means we should close
if (serverClosing) {
return ready(new Error('Server was closed before it could start'))
}
serverStarted = true
const addr = server.address()
logger.info(`Started at ${opts.host || addr.host || 'localhost'}:${addr.port}`)
ready(err, app, server)
})
}