license import * as express from 'express' ; import { NodeHttpTransport } from '@improbable-eng/grpc-web-node-http-transport' ; import { bankingServiceDefinition } from './service' ; import { getBankingHandler } from './handler' ; import { AuthServerContextConnector , AuthClientContextConnector , } from './auth_context' ; import * as http from 'http' ; 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 ( bankingServiceDefinition , getBankingHandler ( ) , { serverContextConnector : new AuthServerContextConnector ( 'u1' ) , } ) ) ; 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 ( bankingServiceDefinition , { remoteAddress , clientContextConnector : new AuthClientContextConnector ( 'u1' ) , getGrpcWebTransport : NodeHttpTransport ( ) , } ) ; const balanceResponseBefore = await client . getBalance ( { } ) ; console . log ( 'Balance is' , balanceResponseBefore . value ) ; console . log ( 'Transfering...' ) ; await client . transfer ( { toUserId : 'u2' , amount : balanceResponseBefore . value / 2 , } ) ; const balanceResponseAfter = await client . getBalance ( { } ) ; console . log ( 'Now balance is' , balanceResponseAfter . value ) ; { const unauthenticatedClient = ModuleRpcProtocolClient . getRpcClient ( bankingServiceDefinition , { remoteAddress , clientContextConnector : new AuthClientContextConnector ( 'u2' ) , getGrpcWebTransport : NodeHttpTransport ( ) , } ) ; try { await unauthenticatedClient . getBalance ( { } ) ; } catch ( err ) { console . log ( 'Expected error' , err ) ; } } }