service-core/core/http.mjs

70 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-09-09 15:41:05 +00:00
import http from 'http'
export default class HttpServer {
constructor() {
this.active = {
app: false,
manage: false,
dev: false,
}
this.sockets = {
app: new Set(),
manage: new Set(),
dev: new Set(),
}
this._context = 'dev'
}
setContext(name) {
if (name !== 'app' && name !== 'manage' && name !== 'dev') {
throw new Error('Cannot call setContext with values other than app or manage')
}
2020-09-12 20:31:36 +00:00
this._context = name
2020-09-09 15:41:05 +00:00
}
createServer(opts, listener) {
return this._createServer(this._context, opts, listener)
}
_createServer(name, opts, listener) {
let server = http.createServer(opts, listener)
server.on('connection', (socket) => {
this.sockets[name].add(socket)
socket.once('close', () => {
this.sockets[name].delete(socket)
})
})
this.active[name] = server
return server
}
getServer(name) {
return this.active[name]
}
closeServer(name) {
2020-09-12 20:31:36 +00:00
if (!this.active[name]) return console.log('no active found with name', name, this.active)
2020-09-09 15:41:05 +00:00
return new Promise((res, rej) => {
this.sockets[name].forEach(function(socket) {
socket.destroy()
})
this.sockets[name].clear()
this.active[name].close(function(err) {
if (err) return rej(err)
2020-09-12 20:31:36 +00:00
// Waiting 1 second for it to close down
setTimeout(res, 1000)
2020-09-09 15:41:05 +00:00
})
})
}
getCurrentServer() {
return this.active[this._context]
}
}