params: add FromAny function

Creating RPC server parameters from any data can be useful. Refs. #2909.
This commit is contained in:
Roman Khimov 2023-02-15 10:05:10 +03:00
parent 1d6e48ee78
commit e496084bee
2 changed files with 49 additions and 1 deletions

View file

@ -1,12 +1,29 @@
package params
import "fmt"
import (
"encoding/json"
"fmt"
)
type (
// Params represents the JSON-RPC params.
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
// index if it exists.
func (p Params) Value(index int) *Param {

View 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)
}