import { grpc } from '@improbable-eng/grpc-web' ; import { Context , ContextInterface } from '@textile/context' ; import { WebsocketTransport } from '@textile/grpc-transport' ; export interface ServiceError { message : string ; code : number ; metadata : grpc . Metadata ; } export class GrpcConnection { public serviceHost : string ; public rpcOptions : grpc . RpcOptions ; param context constructor ( public context = new Context ( ) , debug = false ) { const transport = WebsocketTransport ( ) ; this . serviceHost = context . host ; this . rpcOptions = { transport , debug , } ; grpc . setDefaultTransport ( transport ) ; } public unary < R extends grpc . ProtobufMessage , T extends grpc . ProtobufMessage , M extends grpc . UnaryMethodDefinition < R , T > > ( methodDescriptor , req , ctx ? ) { return new Promise < T > ( ( resolve , reject ) => { const metadata = ctx ? { ... ctx . toJSON ( ) } : { ... this . context . toJSON ( ) } ; grpc . unary ( methodDescriptor , { request : req , host : this . serviceHost , transport : this . rpcOptions . transport , debug : this . rpcOptions . debug , metadata , onEnd : ( res ) => { const { status , statusMessage , message } = res ; if ( status === grpc . Code . OK ) { resolve ( message as any ) ; } else { const err = { message : statusMessage , code : status , metadata , } ; reject ( err ) ; } } , } ) ; } ) ; } }