-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.js
65 lines (56 loc) · 1.88 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
var async = require('async')
var has = require('lodash.has')
var merge = require('lodash.merge')
var once = require('lodash.once')
var duration = require('parse-duration')
var format = require('util').format
var enableDestroy = require('server-destroy')
module.exports = function(options) {
var config
var app
var logger
var server
var destroy
function init(dependencies, cb) {
config = merge({ host: '0.0.0.0', shutdown: { delay: '5s' } }, dependencies.config)
app = dependencies.app
logger = dependencies.logger || app.locals.logger || console
cb()
}
function validate(cb) {
if (!app) return cb(new Error('app is required'))
if (!has(config, 'port')) return cb(new Error('config.port is required'))
cb()
}
function start(cb) {
logger.info(format('Starting server on %s:%d', config.host, config.port))
server = app.listen(config.port, config.host, cb)
config.hasOwnProperty('requestTimeout') && (server.requestTimeout = config.requestTimeout)
enableDestroy(server)
}
function stop(cb) {
if (!server) return cb()
var next = once(cb)
scheduleDestroy(next)
close(next)
}
function scheduleDestroy(cb) {
destroy = setTimeout(function() {
logger.info(format('Server did not shutdown gracefully within %s', config.shutdown.delay))
logger.warn(format('Forcefully stopping server on %s:%d', config.host, config.port))
server.destroy(cb)
}, duration(config.shutdown.delay))
destroy.unref()
}
function close(cb) {
logger.info(format('Stopping server on %s:%d', config.host, config.port))
server.close(function() {
clearTimeout(destroy)
cb()
})
}
return {
start: async.seq(init, validate, start),
stop: stop
}
}