Skip to content

Commit

Permalink
add recursive call to createRenameMap in the encoding to handle field…
Browse files Browse the repository at this point in the history
…s of embedded structs.
  • Loading branch information
badarsebard committed May 25, 2024
1 parent a86f693 commit d910928
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
9 changes: 6 additions & 3 deletions internal/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,13 @@ func Normalize(value interface{}) (interface{}, error) {
return nil, fmt.Errorf("invalid dtype %s", rType.Name())
}

func createRenameMap(rv reflect.Value) map[string]string {
renameMap := make(map[string]string)
func createRenameMap(rv reflect.Value, renameMap map[string]string) map[string]string {
for i := 0; i < rv.NumField(); i++ {
fieldType := rv.Type().Field(i)
if fieldType.Anonymous {
createRenameMap(rv.Field(i), renameMap)
continue
}

renameTo := fieldType.Name
renameFrom := fieldType.Name
Expand Down Expand Up @@ -205,7 +208,7 @@ func rename(fields map[string]interface{}, v interface{}) map[string]interface{}
return nil
}

renameMap := createRenameMap(rv)
renameMap := createRenameMap(rv, make(map[string]string))
m := make(map[string]interface{})
for key, value := range fields {
renamedFieldName := renameMap[key]
Expand Down
6 changes: 3 additions & 3 deletions internal/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

type BaseModel struct {
ID string `clover:""`
ID string `clover:"_id" json:"cloverId"`
}

type TestStruct struct {
Expand Down Expand Up @@ -69,7 +69,7 @@ func TestNormalize(t *testing.T) {

require.Nil(t, m["uint"]) // testing omitempty
require.Equal(t, m["IntPtr"], int64(100))
require.Equal(t, m["ID"], "UID")
require.Equal(t, m["_id"], "UID")

s1 := &TestStruct{}
err = Convert(m, s1)
Expand Down Expand Up @@ -168,4 +168,4 @@ func TestJsonTag(t *testing.T) {
require.NoError(t, err)

require.Equal(t, s, &ns)
}
}

0 comments on commit d910928

Please sign in to comment.