Skip to content

Commit

Permalink
Fix: Union types are now flattened (i.e. if a union has a type which …
Browse files Browse the repository at this point in the history
…is another union, they will be combined). (#4)
  • Loading branch information
dorner authored Feb 27, 2024
1 parent 6170308 commit 4dab99a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# UNRELEASED

- Fix: Union types are now flattened (i.e. if a union has a type which is another union, they will be combined).
- Feature / breaking change: add `preserve_non_string_maps` and change default behavior to turn all maps into string-keyed ones.
- Fix: Flatten any instances of `{type: { type: ... } }`

Expand Down
37 changes: 23 additions & 14 deletions avro/union.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,41 @@
package avro

import "fmt"
import (
"fmt"
"github.com/iancoleman/orderedmap"
"reflect"
)

type Union struct {
Types []Type
}

func (u Union) ToJSON(types *TypeRepo) (any, error) {
flattened := u.flatten()
jsonSlice := make([]any, len(flattened))
for i, unionType := range flattened {
var jsonSlice []any
for _, unionType := range u.Types {
typeJson, err := unionType.ToJSON(types)
if err != nil {
return nil, fmt.Errorf("error parsing union type: %w", err)
}
jsonSlice[i] = typeJson
jsonSlice = append(jsonSlice, typeJson)
}
return jsonSlice, nil
return flatten(jsonSlice), nil
}

func (u Union) flatten() []Type {
var flattened []Type
for _, unionType := range u.Types {
switch unionType.(type) {
case Union:
flattened = append(flattened, unionType.(Union).flatten()...)
default:
flattened = append(flattened, unionType)
func flatten(slice []any) []any {
var flattened []any
for _, jsonType := range slice {
jsonMap, ok := jsonType.(*orderedmap.OrderedMap)
LogMsg("%v", reflect.TypeOf(jsonType))
if ok {
typeArr, ok := jsonMap.Get("type")
if ok && reflect.TypeOf(typeArr).Kind() == reflect.Slice {
flattened = append(flattened, typeArr.([]any)...)
} else {
flattened = append(flattened, jsonType)
}
} else {
flattened = append(flattened, jsonType)
}
}
return flattened
Expand Down

0 comments on commit 4dab99a

Please sign in to comment.