2020-09-09 15:41:05 +00:00
|
|
|
import http from 'http'
|
|
|
|
|
|
|
|
export default class HttpServer {
|
2020-09-13 04:36:33 +00:00
|
|
|
constructor(config) {
|
2020-09-09 15:41:05 +00:00
|
|
|
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]
|
|
|
|
}
|
|
|
|
|
2020-09-13 04:36:33 +00:00
|
|
|
async closeServer(name) {
|
|
|
|
if (!this.active[name]) return false
|
2020-09-09 15:41:05 +00:00
|
|
|
|
2020-09-13 04:36:33 +00:00
|
|
|
try {
|
2020-09-13 15:23:21 +00:00
|
|
|
return await new Promise((res, rej) => {
|
2020-09-13 04:36:33 +00:00
|
|
|
this.sockets[name].forEach(function(socket) {
|
|
|
|
socket.destroy()
|
|
|
|
})
|
|
|
|
this.sockets[name].clear()
|
|
|
|
|
|
|
|
this.active[name].close(function(err) {
|
|
|
|
if (err) return rej(err)
|
|
|
|
|
|
|
|
// Waiting 1 second for it to close down
|
|
|
|
setTimeout(function() { res(true) }, 1000)
|
|
|
|
})
|
2020-09-09 15:41:05 +00:00
|
|
|
})
|
2020-09-13 04:36:33 +00:00
|
|
|
} catch (err) {
|
|
|
|
throw new Error(`Error closing ${name}: ${err.message}`)
|
|
|
|
}
|
2020-09-09 15:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
getCurrentServer() {
|
|
|
|
return this.active[this._context]
|
|
|
|
}
|
|
|
|
}
|