Skip to content

Commit 4dab99a

Browse files
authored
Fix: Union types are now flattened (i.e. if a union has a type which is another union, they will be combined). (#4)
1 parent 6170308 commit 4dab99a

File tree

2 files changed

+24
-14
lines changed

2 files changed

+24
-14
lines changed

CHANGELOG

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
# UNRELEASED
44

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

avro/union.go

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,41 @@
11
package avro
22

3-
import "fmt"
3+
import (
4+
"fmt"
5+
"github.com/iancoleman/orderedmap"
6+
"reflect"
7+
)
48

59
type Union struct {
610
Types []Type
711
}
812

913
func (u Union) ToJSON(types *TypeRepo) (any, error) {
10-
flattened := u.flatten()
11-
jsonSlice := make([]any, len(flattened))
12-
for i, unionType := range flattened {
14+
var jsonSlice []any
15+
for _, unionType := range u.Types {
1316
typeJson, err := unionType.ToJSON(types)
1417
if err != nil {
1518
return nil, fmt.Errorf("error parsing union type: %w", err)
1619
}
17-
jsonSlice[i] = typeJson
20+
jsonSlice = append(jsonSlice, typeJson)
1821
}
19-
return jsonSlice, nil
22+
return flatten(jsonSlice), nil
2023
}
2124

22-
func (u Union) flatten() []Type {
23-
var flattened []Type
24-
for _, unionType := range u.Types {
25-
switch unionType.(type) {
26-
case Union:
27-
flattened = append(flattened, unionType.(Union).flatten()...)
28-
default:
29-
flattened = append(flattened, unionType)
25+
func flatten(slice []any) []any {
26+
var flattened []any
27+
for _, jsonType := range slice {
28+
jsonMap, ok := jsonType.(*orderedmap.OrderedMap)
29+
LogMsg("%v", reflect.TypeOf(jsonType))
30+
if ok {
31+
typeArr, ok := jsonMap.Get("type")
32+
if ok && reflect.TypeOf(typeArr).Kind() == reflect.Slice {
33+
flattened = append(flattened, typeArr.([]any)...)
34+
} else {
35+
flattened = append(flattened, jsonType)
36+
}
37+
} else {
38+
flattened = append(flattened, jsonType)
3039
}
3140
}
3241
return flattened

0 commit comments

Comments
 (0)