Add foreground service, some cleanup, and start websocket server

This commit is contained in:
2022-07-13 21:35:18 -05:00
parent 4d7769de56
commit 6476416c67
12 changed files with 158 additions and 43 deletions

View File

@@ -0,0 +1,50 @@
import {Unit, UnitStatus} from '../lifecycle/Unit'
import {Inject, Singleton} from '../di'
import * as WebSocket from 'ws'
import {HTTPServer} from './HTTPServer'
import {Logging} from './Logging'
import {ErrorWithContext} from '../util'
import {Request} from '../http/lifecycle/Request'
@Singleton()
export class WebsocketServer extends Unit {
@Inject()
protected readonly http!: HTTPServer
@Inject()
protected readonly logging!: Logging
protected server?: WebSocket.Server
public async up(): Promise<void> {
// Make sure the HTTP server is started. Otherwise, this is going to fail anyway
if ( this.http.status !== UnitStatus.Started ) {
throw new ErrorWithContext('Cannot start WebsocketServer without HTTPServer.', {
suggestion: 'Make sure the HTTPServer is registered in your Units.extollo.ts file, and it is listed before the WebsocketServer.',
})
}
// Start the websocket server
this.logging.info('Starting WebSocket server...')
this.server = new WebSocket.Server<WebSocket.WebSocket>({
server: this.http.getServer(),
})
// Register the websocket handler
this.server.on('connection', (ws, request) => {
this.logging.info('Got WebSocket connection! ' + request.method)
const extolloReq = new Request(request)
this.logging.debug(ws)
this.logging.debug(request)
})
}
public down(): Promise<void> {
return new Promise(res => {
// Stop the websocket server, if it exists
if ( this.server ) {
this.server.close(() => res())
}
})
}
}