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 { // 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({ 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 { return new Promise(res => { // Stop the websocket server, if it exists if ( this.server ) { this.server.close(() => res()) } }) } }