Allow JSON encoded labels when quering resources
This commit is contained in:
@@ -2,6 +2,7 @@ package label
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/cortezaproject/corteza-server/pkg/handle"
|
||||
"github.com/cortezaproject/corteza-server/pkg/label/types"
|
||||
@@ -42,14 +43,23 @@ func Changed(old, new map[string]string) bool {
|
||||
}
|
||||
|
||||
// ParseStrings converts slice of strings with "key=val" format into
|
||||
func ParseStrings(ss []string) (map[string]string, error) {
|
||||
func ParseStrings(ss []string) (m map[string]string, err error) {
|
||||
if len(ss) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
m := make(map[string]string)
|
||||
m = make(map[string]string)
|
||||
|
||||
for _, s := range ss {
|
||||
if strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}") {
|
||||
// assume json
|
||||
if err = json.Unmarshal([]byte(s), &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
kv := strings.SplitN(s, "=", 2)
|
||||
if len(kv) != 2 {
|
||||
return nil, fmt.Errorf("invalid label format")
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package label
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChanged(t *testing.T) {
|
||||
tests := []struct {
|
||||
@@ -9,7 +12,6 @@ func TestChanged(t *testing.T) {
|
||||
new map[string]string
|
||||
want bool
|
||||
}{
|
||||
// TODO: Add test cases.
|
||||
{
|
||||
"2x nil",
|
||||
nil,
|
||||
@@ -55,3 +57,44 @@ func TestChanged(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseStrings(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
labels []string
|
||||
want map[string]string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
"set of pairs",
|
||||
[]string{"aa=b"},
|
||||
map[string]string{"aa": "b"},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"empty json",
|
||||
[]string{`{}`},
|
||||
map[string]string{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"json",
|
||||
[]string{`{"aa":"b"}`},
|
||||
map[string]string{"aa": "b"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseStrings(tt.labels)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("ParseStrings() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("ParseStrings() got = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user