-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
90 lines (71 loc) · 2.13 KB
/
app.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
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const errors = require('./errors')
const logger = require('./logger')
let server
const initialize = () => {
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// //generate API docs
// app.get('/swagger.json', function(req, res) {
// res.json(require('./swagger')())
// })
const routes = require('./routes')
for(const path in routes) {
logger.debug('Register path /%s', path)
app.use(`/${path}`, routes[path])
}
// last call catch 404 and forward to error handler
app.use(function(req, res, next) {
next(new errors.NotFound())
})
// error handlers
app.use(function(err, req, res, next) {
if(err instanceof errors.HttpError) {
res.status(err.code)
res.json(err.toJSON())
return
}
if(err.code && (err.code >= 400 && err.code <= 510)) {
res.status(err.code)
res.json({
code: err.code,
message: err.message
})
return
}
logger.error('Error: %s', err.message)
logger.debug(err.stack)
const internalError = new errors.InternalServer()
res.status(internalError.code)
res.json(internalError.toJSON())
})
return app
}
const start = (port) => {
if(server) return Promise.resolve()
const app = initialize()
server = require('http').Server(app)
return new Promise(function(resolve, reject) {
server.listen(port, function(err) {
if(err) return reject(err)
logger.info(`Server listening on ::${port}`)
resolve()
})
})
}
const stop = () => {
return new Promise(function(resolve, reject) {
if(!server) return resolve()
server.close(function(err) {
if(err) return reject(err)
server = null
logger.info('Server stopped')
resolve()
})
})
}
module.exports = { start, stop }