params: add FromAny function
Creating RPC server parameters from any data can be useful. Refs. #2909.
This commit is contained in:
parent
1d6e48ee78
commit
e496084bee
2 changed files with 49 additions and 1 deletions
|
@ -1,12 +1,29 @@
|
||||||
package params
|
package params
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
// Params represents the JSON-RPC params.
|
// Params represents the JSON-RPC params.
|
||||||
Params []Param
|
Params []Param
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// FromAny allows to create Params for a slice of abstract values (by
|
||||||
|
// JSON-marshaling them).
|
||||||
|
func FromAny(arr []interface{}) (Params, error) {
|
||||||
|
var res Params
|
||||||
|
for i := range arr {
|
||||||
|
b, err := json.Marshal(arr[i])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("wrong parameter %d: %w", i, err)
|
||||||
|
}
|
||||||
|
res = append(res, Param{RawMessage: json.RawMessage(b)})
|
||||||
|
}
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Value returns the param struct for the given
|
// Value returns the param struct for the given
|
||||||
// index if it exists.
|
// index if it exists.
|
||||||
func (p Params) Value(index int) *Param {
|
func (p Params) Value(index int) *Param {
|
||||||
|
|
31
pkg/services/rpcsrv/params/params_test.go
Normal file
31
pkg/services/rpcsrv/params/params_test.go
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
package params
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParamsFromAny(t *testing.T) {
|
||||||
|
str := "jajaja"
|
||||||
|
|
||||||
|
ps, err := FromAny([]interface{}{str, smartcontract.Parameter{Type: smartcontract.StringType, Value: str}})
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, 2, len(ps))
|
||||||
|
|
||||||
|
resStr, err := ps[0].GetString()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, resStr, str)
|
||||||
|
|
||||||
|
resFP, err := ps[1].GetFuncParam()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, resFP.Type, smartcontract.StringType)
|
||||||
|
resStr, err = resFP.Value.GetString()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, resStr, str)
|
||||||
|
|
||||||
|
// Invalid item.
|
||||||
|
_, err = FromAny([]interface{}{smartcontract.Parameter{Type: smartcontract.IntegerType, Value: str}})
|
||||||
|
require.Error(t, err)
|
||||||
|
}
|
Loading…
Reference in a new issue