service-core/core/http.mjs

50 lines
1 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
})
})
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) return rej(err)
this.active = null
// Waiting 1 second for it to close down
setTimeout(function() {res() }, 1000)
})
})
2020-09-09 15:41:05 +00:00
}
}