Skip to content

Commit

Permalink
fix: use AsMap when available
Browse files Browse the repository at this point in the history
  • Loading branch information
moshloop committed Sep 18, 2024
1 parent d6d409c commit 106141b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
11 changes: 11 additions & 0 deletions serialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gomplate
import (
"time"

"github.com/google/uuid"
"github.com/ohler55/ojg"
"github.com/ohler55/ojg/alt"
"github.com/ohler55/ojg/jp"
Expand All @@ -24,6 +25,10 @@ var opts = oj.Options{
WriteLimit: 1024,
}

type AsMapper interface {
AsMap(fields ...string) map[string]any
}

// Serialize iterates over each key-value pair in the input map
// serializes any struct value to map[string]any.
func Serialize(in map[string]any) (map[string]any, error) {
Expand All @@ -36,6 +41,12 @@ func Serialize(in map[string]any) (map[string]any, error) {
nativeTypes := make(map[string]any, len(in))
jp.Walk(in, func(path jp.Expr, value any) {
switch v := value.(type) {
case AsMapper:
nativeTypes[path.String()] = v.AsMap()
case uuid.UUID:
nativeTypes[path.String()] = v.String()
case *uuid.UUID:
nativeTypes[path.String()] = v.String()
case time.Duration:
nativeTypes[path.String()] = v
}
Expand Down
13 changes: 13 additions & 0 deletions tests/serialize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/flanksource/gomplate/v3/data"
_ "github.com/flanksource/gomplate/v3/js"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
_ "github.com/robertkrimen/otto/underscore"
)

Expand All @@ -27,6 +28,18 @@ func Test_serialize(t *testing.T) {
want map[string]any
wantErr bool
}{
{name: "nested uuid",
in: map[string]any{
"container": map[string]any{
"id": uuid.MustParse("962f999c-a9bd-40a4-80bf-47c84b1ad750"),
},
},
want: map[string]any{
"container": map[string]any{
"id": "962f999c-a9bd-40a4-80bf-47c84b1ad750",
},
},
},
{
name: "duration",
in: map[string]any{
Expand Down

0 comments on commit 106141b

Please sign in to comment.