/ cli / source / watchers / helpers / CommandLinkIntegration.ts
CommandLinkIntegration.ts
 1  import { CommandLink, CommandLinkErrorHandler, CommandLinkResponseHandler } from './CommandLink'
 2  import logSymbols from 'log-symbols'
 3  
 4  export class CommandLinkIntegration {
 5      private retryTimeout: NodeJS.Timeout
 6      readonly link: CommandLink
 7  
 8      private readonly address: string
 9      private readonly retryMs: number
10      private readonly responseHandler: CommandLinkResponseHandler
11      private readonly errorHandler: CommandLinkErrorHandler
12  
13      constructor( address: string, retryTimeMs : number = 5000, responseHandler: CommandLinkResponseHandler = null, errorHandler: CommandLinkErrorHandler = null ) {
14          this.address = address
15          this.retryMs = retryTimeMs
16          this.responseHandler = responseHandler
17          this.errorHandler = errorHandler
18  
19          this.link = new CommandLink()
20          this.initializeLink()
21      }
22  
23      private initializeLink() : void {
24          this.link.start( this.address, this.responseHandler, this.onLinkError.bind( this ), this.onLinkConnected.bind( this ) )
25  
26          if ( this.retryTimeout ) {
27              this.retryTimeout = null
28          }
29      }
30  
31      private onLinkError( error? : Error ) : void {
32          if ( this.errorHandler ) {
33              this.errorHandler( error )
34          }
35  
36          console.log( logSymbols.error, `Failed command link connection. Retrying connection in ${this.retryMs} ms` )
37          this.retryTimeout = setTimeout( this.initializeLink.bind( this ), this.retryMs )
38      }
39  
40      private onLinkConnected() : void {
41          process.stdout.clearLine( 1 )
42          console.log( logSymbols.success, `CommandLink is connected to game server on ${this.address}` )
43      }
44  }