import { JsonRpcRequest , JsonRpcSuccessResponse , RpcServer , isJsonRpcRequest , } from '../../../types' ; import { buildJsonRpcError } from './json-rpc-errors' ; import { ExpressHttpServer } from './express-http-server' ; /**
 * Basic JSON-RPC server.
 */ export class JsonRpcServer extends ExpressHttpServer implements RpcServer { param methods param port param hostname constructor ( private methods = { } , hostname , port , middleware ? ) { super ( port , hostname , middleware ) ; } /**
     * Initializes app routes.
     */ protected initRoutes ( ) { this . app . post ( '/' , async ( req , res ) => { const request = req . body ; if ( ! isJsonRpcRequest ( request ) ) { return res . json ( buildJsonRpcError ( 'INVALID_REQUEST' , null ) ) ; } if ( ! ( request . method in this . methods ) ) { return res . json ( buildJsonRpcError ( 'METHOD_NOT_FOUND' , request . id ) ) ; } let result ; try { result = await this . methods [ request . method ] ( request . params ) ; } catch ( err ) { return res . json ( buildJsonRpcError ( 'INTERNAL_ERROR' , request . id ) ) ; } const response = { jsonrpc : '2.0' , id : request . id , result , } ; return res . json ( response ) ; } ) ; } param name param method public register ( name , method ) { if ( name in this . methods ) { throw new Error ( `method already registered: ${ name }` ) ; } this . methods [ name ] = method ; } }