Fix rpc/lib/...

This commit is contained in:
Jae Kwon
2018-04-05 15:45:11 -07:00
parent e4492afbad
commit 3037b5b7ca
10 changed files with 132 additions and 72 deletions

View File

@ -7,6 +7,7 @@ import (
"strings"
"github.com/pkg/errors"
"github.com/tendermint/go-amino"
tmpubsub "github.com/tendermint/tmlibs/pubsub"
)
@ -33,8 +34,16 @@ func (req RPCRequest) String() string {
return fmt.Sprintf("[%s %s]", req.ID, req.Method)
}
func MapToRequest(id string, method string, params map[string]interface{}) (RPCRequest, error) {
payload, err := json.Marshal(params)
func MapToRequest(cdc *amino.Codec, id string, method string, params map[string]interface{}) (RPCRequest, error) {
var params_ = make(map[string]json.RawMessage, len(params))
for name, value := range params {
valueJSON, err := cdc.MarshalJSON(value)
if err != nil {
return RPCRequest{}, err
}
params_[name] = valueJSON
}
payload, err := json.Marshal(params_) // NOTE: Amino doesn't handle maps yet.
if err != nil {
return RPCRequest{}, err
}
@ -42,8 +51,16 @@ func MapToRequest(id string, method string, params map[string]interface{}) (RPCR
return request, nil
}
func ArrayToRequest(id string, method string, params []interface{}) (RPCRequest, error) {
payload, err := json.Marshal(params)
func ArrayToRequest(cdc *amino.Codec, id string, method string, params []interface{}) (RPCRequest, error) {
var params_ = make([]json.RawMessage, len(params))
for i, value := range params {
valueJSON, err := cdc.MarshalJSON(value)
if err != nil {
return RPCRequest{}, err
}
params_[i] = valueJSON
}
payload, err := json.Marshal(params_) // NOTE: Amino doesn't handle maps yet.
if err != nil {
return RPCRequest{}, err
}
@ -75,12 +92,12 @@ type RPCResponse struct {
Error *RPCError `json:"error,omitempty"`
}
func NewRPCSuccessResponse(id string, res interface{}) RPCResponse {
func NewRPCSuccessResponse(cdc *amino.Codec, id string, res interface{}) RPCResponse {
var rawMsg json.RawMessage
if res != nil {
var js []byte
js, err := json.Marshal(res)
js, err := cdc.MarshalJSON(res)
if err != nil {
return RPCInternalError(id, errors.Wrap(err, "Error marshalling response"))
}

View File

@ -8,6 +8,7 @@ import (
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/tendermint/go-amino"
)
type SampleResult struct {
@ -16,8 +17,9 @@ type SampleResult struct {
func TestResponses(t *testing.T) {
assert := assert.New(t)
cdc := amino.NewCodec()
a := NewRPCSuccessResponse("1", &SampleResult{"hello"})
a := NewRPCSuccessResponse(cdc, "1", &SampleResult{"hello"})
b, _ := json.Marshal(a)
s := `{"jsonrpc":"2.0","id":"1","result":{"Value":"hello"}}`
assert.Equal(string(s), string(b))