shogowada / json-rpc-2.0

Let your client and server talk over function calls under JSON-RPC 2.0 spec. Strongly typed. No external dependencies.

Home Page:https://www.npmjs.com/package/json-rpc-2.0

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Method callback not working

ethereumdegen opened this issue · comments

Using 1.5.1 and 1.4.1 with this code :

import fs from 'fs'
import http from 'http'
import https from 'https'
import path from 'path'

import cors from 'cors'
import express from 'express'
import bodyParser from 'body-parser'

import {JSONRPCServer } from 'json-rpc-2.0'

export interface ModuleRpcRequest {

endpointName: string
moduleName: string
params: any

}

export interface ModuleRpcEndpoint {

name: string
route: string

}

let PORT = process.env.PORT ? process.env.PORT : 8000

export default class WebServer {
server: https.Server | http.Server | undefined

app:any

appListener: any

constructor( public serverConfig: any ) {

this.app = express()
this.app.use(bodyParser.json());

if(serverConfig.port){
  PORT = serverConfig.port
} 

}

async start( ): Promise {

const jserver = new JSONRPCServer();
jserver.addMethod("echo", ( ) => {
  console.log('echo')
  return 'echo'
});

this.app.post("/", (req:any, res:any) => {
    
const jsonRPCRequest = req.body;
console.log('got post',jsonRPCRequest)
// server.receive takes a JSON-RPC request and returns a promise of a JSON-RPC response.
// It can also receive an array of requests, in which case it may return an array of responses.
// Alternatively, you can use server.receiveJSON, which takes JSON string as is (in this case req.body).
jserver.receive(jsonRPCRequest).then((jsonRPCResponse:any) => {

  console.log('meep', jsonRPCResponse)
  if (jsonRPCResponse) {
    console.log('returning ', jsonRPCResponse)
    res.json(jsonRPCResponse);
  } else {
    console.log('no response ', jsonRPCResponse)
    // If response is absent, it was a JSON-RPC notification method.
    // Respond with no content status (204).
    res.sendStatus(204);
  }
});

});

  this.appListener = this.app.listen(PORT);

  console.log(`Backend Server listening on port ${PORT} using http`)

}

async stop( ){
if(this.appListener){
this.appListener.close()
}

}
}

When i hit it with this POST :

{
"jsonrpc": "2.0",
"method": "echo",
"params": [ "dogs" ]

}

i get this :

Backend Server listening on port 6102 using http
got post { jsonrpc: '2.0', method: 'echo', params: [ 'dogs' ] }
echo
meep null
no response null

which makes absolutely no sense because the method 'echo' is running (its printing echo) but it wont return into the .then and into the jsonRPCResponse at all. that is null.. HOW

I forgot to add id:"0" to input