You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.7 KiB
51 lines
1.7 KiB
2 years ago
|
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())
|
||
|
}
|
||
|
})
|
||
|
}
|
||
|
}
|