Add foreground service, some cleanup, and start websocket server
This commit is contained in:
50
src/service/WebsocketServer.ts
Normal file
50
src/service/WebsocketServer.ts
Normal 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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user