license import * as express from 'express' ; import { numberServiceDefinition , NumberService } from './service' ; import * as http from 'http' ; import { NodeHttpTransport } from '@improbable-eng/grpc-web-node-http-transport' ; import { getNumberHandler } from './handler' ; import { ModuleRpcClient } from '../../client' ; import { ModuleRpcCommon } from '../../common' ; import { AssertionError } from 'assert' ; import { ModuleRpcContextServer } from '../../context/server' ; import { ModuleRpcProtocolServer } from '../../protocol/server' ; import { ModuleRpcProtocolClient } from '../../protocol/client' ; main ( ) . catch ( err => { console . error ( err ) ; process . exit ( 1 ) ; } ) ; async function main ( ) { const server = setupServer ( ) ; try { await clientInteraction ( `http://127.0.0.1:${ server . address ( ) . port }/api` ) ; } finally { server . close ( ) ; } } function setupServer ( ) { const app = express ( ) ; app . use ( '/api' , ModuleRpcProtocolServer . registerRpcRoutes ( numberServiceDefinition , getNumberHandler ( ) , { serverContextConnector : new ModuleRpcContextServer . EmptyServerContextConnector ( ) , } ) ) ; const server = http . createServer ( app ) . listen ( ) ; const port = server . address ( ) . port ; app . set ( 'port' , port ) ; return server ; } async function clientInteraction ( remoteAddress ) { const client = ModuleRpcProtocolClient . getRpcClient ( numberServiceDefinition , { remoteAddress , getGrpcWebTransport : NodeHttpTransport ( ) , } ) ; const { value } = await client . increment ( { value : 10 } ) ; console . log ( 'Value is' , value ) ; const result = await ModuleRpcClient . streamAsPromise ( streamNumbers ( client ) ) ; console . log ( 'ping: all messages:' , result ) ; try { const stream = streamNumbers ( client ) . on ( 'ready' , ( ) => { setTimeout ( ( ) => stream . cancel ( ) , 2000 ) ; } ) ; await ModuleRpcClient . streamAsPromise ( stream ) ; throw new AssertionError ( { message : 'expected cancelation error' } ) ; } catch ( err ) { console . error ( 'Expected cancelation error:' , err ) ; } } function streamNumbers ( client ) { return client . streamNumbers ( { max : 3 , sleepMs : 500 } ) . on ( 'ready' , ( ) => { console . log ( 'ping: onReady()' ) ; } ) . on ( 'message' , message => { console . log ( `ping: onMessage(${ JSON . stringify ( message ) })` ) ; } ) . on ( 'canceled' , ( ) => { console . log ( 'ping: canceled' ) ; } ) . on ( 'error' , err => { console . log ( 'ping: error (not supposed to happen):' , err ) ; } ) ; }