import { Sub } from './nats' ; import { EventEmitter } from 'events' ; hidden export class Subscriptions extends EventEmitter { mux ! : Sub ; subs : { [ key ] : Sub ; } = { } ; sidCounter : number = 0 ; length : number = 0 ; constructor ( ) { super ( ) ; EventEmitter . call ( this ) ; } add ( s ) { this . sidCounter ++ ; this . length ++ ; s . sid = this . sidCounter ; this . subs [ s . sid ] = s ; let se = { sid : s . sid , subject : s . subject , queue : s . queue } ; this . emit ( 'subscribe' , se ) ; return s ; } setMux ( s ) { this . mux = s ; return s ; } getMux ( ) { return this . mux ; } get ( sid ) { if ( sid in this . subs ) { return this . subs [ sid ] ; } return null ; } all ( ) { let buf = [ ] ; for ( let sid in this . subs ) { let sub = this . subs [ sid ] ; buf . push ( sub ) ; } return buf ; } cancel ( s ) { if ( s && s . timeout ) { clearTimeout ( s . timeout ) ; delete s . timeout ; } if ( s . sid in this . subs ) { let sub = this . subs [ s . sid ] ; let se = { sid : sub . sid , subject : sub . subject , queue : sub . queue } ; delete this . subs [ s . sid ] ; this . length -- ; this . emit ( 'unsubscribe' , se ) ; } } close ( ) { let subs = this . all ( ) ; for ( let i = 0 ; i < subs . length ; i ++ ) { this . cancel ( subs [ i ] ) ; } } }