license import { ModuleRpcCommon } from '../../common' ; import { ModuleRpcServer } from '../../server' ; import { BankingService } from './service' ; import { AuthRequestContext } from './auth_context' ; export type BankingHandler = ModuleRpcServer . ServiceHandlerFor < BankingService , AuthRequestContext > ; type User = { balance : number ; } ; /**
 * Return a handler where the methods of the BankingService are actually implemented.
 *
 * We wrap it in a function to allow for closures, so that you can have variables scoped
 * to the lifetime of the server (such as the mock store `users` in this instance).
 */ export const getBankingHandler = ( ) : BankingHandler => { const users = { u1 : { balance : 1000 , } , u2 : { balance : 2000 , } , } ; return { async getBalance ( _ , { userId } ) { const user = users [ userId ] ; if ( ! user ) { throw new ModuleRpcServer . ServerRpcError ( ModuleRpcCommon . RpcErrorType . notFound , `user ${ userId } not found` ) ; } return { value : user . balance } ; } , async transfer ( request , { userId } ) { const fromUser = users [ userId ] ; if ( ! fromUser ) { throw new ModuleRpcServer . ServerRpcError ( ModuleRpcCommon . RpcErrorType . internal , `'from' user not found` ) ; } const toUser = users [ request . toUserId ] ; if ( ! toUser ) { throw new ModuleRpcServer . ServerRpcError ( ModuleRpcCommon . RpcErrorType . notFound , undefined , `'to' user not found` ) ; } if ( fromUser . balance < request . amount ) { throw new ModuleRpcServer . ServerRpcError ( ModuleRpcCommon . RpcErrorType . failedPrecondition , undefined , `'from' user has insufficient funds` ) ; } fromUser . balance -= request . amount ; toUser . balance += request . amount ; return { } ; } , } ; } ;