import { EventEmitter } from 'events' ; import { ArgumentNullException } from "../../Errors" ; import { BotMessage , BotResponse } from "../../Models" ; import { ILogger } from "../../Logging" ; import { IBotResponseHandler , IBotConnection } from "../Interfaces" ; import { BotResponseMalformedException } from "../../ServiceErrors" ; export abstract class BotConnectionBase extends EventEmitter implements IBotConnection { readonly botId : string ; protected readonly botName : string ; protected _socket : SocketIO . Socket ; protected _responseTimeout : number ; protected _logger : ILogger ; constructor ( socket , botId , responseTimeout , logger ) { super ( ) ; if ( ! socket ) { throw new ArgumentNullException ( "socket" ) ; } if ( ! botId ) { throw new ArgumentNullException ( "botId" ) ; } if ( ! logger ) { throw new ArgumentNullException ( "logger" ) ; } this . botId = botId ; this . botName = "Unnamed" ; this . _socket = socket ; this . _responseTimeout = responseTimeout ; this . _logger = logger ; this . _socket . on ( 'disconnecting' , ( reason ) => { this . _logger . debug ( `Connection (${ socket . id }) with ${ this . botName } (${ this . botId }) is disconnecting. reason=${ reason }` ) ; } ) ; this . _socket . on ( 'disconnect' , ( reason ) => { this . _logger . info ( `Connection (${ socket . id }) with ${ this . botName } (${ this . botId }) disconnected. reason=${ reason }` ) ; this . emit ( 'disconnected' , this . botId ) ; } ) ; this . _socket . on ( 'error' , ( error ) => { this . _logger . error ( `Connection (${ socket . id }) with ${ this . botName } (${ this . botId }) experienced an error. error=${ error }` ) ; } ) ; } disconnect ( ) { this . _socket . disconnect ( ) ; } sendMessage ( message , responseHandler ) { const event = `message-${ message . id }` ; this . _socket . on ( event , ( data ) => { this . _logger . debug ( `Connection (${ this . _socket . id }) with ${ this . botName } (${ this . botId }) responded with data=${ JSON . stringify ( data ) }` ) ; if ( ! data || ! data . type || typeof data . type !== 'string' || ! data . messages ) { responseHandler ( null , new BotResponseMalformedException ( this . botId ) ) ; return ; } if ( ! Array . isArray ( data . messages ) ) { data . messages = [ data . messages ] ; } const response = new BotResponse ( data . type , data . messages ) ; responseHandler ( response ) ; } ) ; setTimeout ( ( socket , event ) => { socket . removeAllListeners ( event ) ; } , this . _responseTimeout , this . _socket , event ) ; this . _socket . emit ( 'post_message' , message ) ; } rename ( name ) { this . _logger . debug ( `Connection (${ this . _socket . id }) with ${ this . botName } (${ this . botId }) has been renamed to '${ name }'.` ) ; ( this as any ) . botName = name ; } } export default BotConnectionBase ;