service-core/core/http.mjs

63 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-09-09 15:41:05 +00:00
import http from 'http'
import https from 'https'
2020-09-09 15:41:05 +00:00
export default class HttpServer {
constructor(config) {
this.ishttps = false
this.active = null
this.sockets = new Set()
this.creator = http
if (config && config.https) {
this.creator = https
this.ishttps = true
2020-09-09 15:41:05 +00:00
}
}
createServer(opts, listener) {
let server = this.creator.createServer(opts, listener)
2020-09-09 15:41:05 +00:00
server.on('connection', (socket) => {
this.sockets.add(socket)
2020-09-09 15:41:05 +00:00
socket.once('close', () => {
this.sockets.delete(socket)
2020-09-09 15:41:05 +00:00
})
})
server.listenAsync = (port, host) => {
return new Promise((res, rej) => {
server.once('error', rej)
server.listen(port, host || '0.0.0.0', () => {
server.off('error', rej)
res()
})
})
}
this.active = server
2020-09-09 15:41:05 +00:00
return server
}
closeServer() {
if (!this.active) return Promise.resolve()
2020-09-09 15:41:05 +00:00
return new Promise((res, rej) => {
this.sockets.forEach(function(socket) {
socket.destroy()
2020-09-09 15:41:05 +00:00
})
this.sockets.clear()
2020-09-09 15:41:05 +00:00
this.active.close(err => {
if (err) {
if (err.code !== 'ERR_SERVER_NOT_RUNNING') return rej(err)
}
this.active = null
// Waiting 1 second for it to close down
setTimeout(function() {res() }, 100)
})
})
2020-09-09 15:41:05 +00:00
}
}