Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Union types are now flattened (i.e. if a union has a type which … #4

Merged
merged 2 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading