import { Subject } from 'rxjs/Subject' ; import { IGBServiceInfo , } from '../proto' ; import { loadObject , } from './grpc' ; import * as _ from 'lodash' ; export class Service { public disposed : Subject < Service > = new Subject < Service > ( ) ; public stub : any ; public serviceTree : any ; private info : IGBServiceInfo ; private clientIds : number [ ] ; constructor ( private protoTree , clientId , info , private grpc ) { this . clientIds = [ clientId ] ; this . info = info ; } public initStub ( ) { let serv = this . protoTree . lookup ( this . info . service_id ) ; if ( ! serv ) { throw new TypeError ( this . info . service_id + ' was not found.' ) ; } if ( serv . className !== 'Service' ) { throw new TypeError ( this . info . service_id + ' is a ' + serv . className + ' not a Service.' ) ; } let stubctr = loadObject ( this . grpc , serv ) ; this . stub = new stubctr ( this . info . endpoint , this . grpc . credentials . createInsecure ( ) ) ; this . serviceTree = serv ; } public lookupMethod ( methodId ) { for ( let child of this . serviceTree . children ) { if ( child . name === methodId ) { return child ; } } return null ; } public clientAdd ( id ) { if ( this . clientIds . indexOf ( id ) === - 1 ) { this . clientIds . push ( id ) ; } } public clientRelease ( id ) { if ( ! this . clientIds ) { return ; } this . clientIds = _ . without ( this . clientIds , id ) ; if ( this . clientIds . length === 0 ) { this . destroy ( ) ; } } private destroy ( ) { this . clientIds = null ; this . disposed . next ( this ) ; if ( this . stub ) { this . grpc . getClientChannel ( this . stub ) . close ( ) ; } this . stub = null ; this . info = null ; } }