import { Event } from "../../assets/entities/event.entity" ; export class WebSocketConnection { public onEvent ? : ( data : Event ) => void ; public port : number ; public websocket : WebSocket | undefined ; private apiKey : string ; constructor ( port , apiKey , register ? , connected ? ) { this . port = port ; this . apiKey = apiKey ; ( async ( ) => { this . websocket = await this . connect ( register ) ; if ( connected && this . websocket && this . websocket . readyState === this . websocket . OPEN ) connected ( ) ; } ) ( ) ; } private async connect ( register ? ) { const ws = new WebSocket ( `ws://localhost:${ this . port }` ) ; await new Promise < void > ( ( resolve ) => { ws . onopen = ( ) => resolve ( ) ; } ) ; ws . onmessage = ( event ) => { if ( typeof event . data === "string" ) { const json = JSON . parse ( event . data ) ; if ( json . event === "events" && json . data && this . onEvent ) this . onEvent ( json . data ) ; } } ; if ( register ) ws . send ( JSON . stringify ( { event : "register-listener" , data : { "api-key" : this . apiKey , } , } ) ) ; return ws ; } async close ( ) { if ( this . websocket && this . websocket . readyState === this . websocket . OPEN ) this . websocket . close ( ) ; } sendEvent ( event ) { if ( this . websocket && this . websocket . readyState === this . websocket . OPEN ) this . websocket . send ( JSON . stringify ( { event : "events" , data : { "api-key" : this . apiKey , data : event , } , } ) ) ; } }