|
1 | 1 | package avro
|
2 | 2 |
|
3 |
| -import "fmt" |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/iancoleman/orderedmap" |
| 6 | + "reflect" |
| 7 | +) |
4 | 8 |
|
5 | 9 | type Union struct {
|
6 | 10 | Types []Type
|
7 | 11 | }
|
8 | 12 |
|
9 | 13 | 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 { |
13 | 16 | typeJson, err := unionType.ToJSON(types)
|
14 | 17 | if err != nil {
|
15 | 18 | return nil, fmt.Errorf("error parsing union type: %w", err)
|
16 | 19 | }
|
17 |
| - jsonSlice[i] = typeJson |
| 20 | + jsonSlice = append(jsonSlice, typeJson) |
18 | 21 | }
|
19 |
| - return jsonSlice, nil |
| 22 | + return flatten(jsonSlice), nil |
20 | 23 | }
|
21 | 24 |
|
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) |
30 | 39 | }
|
31 | 40 | }
|
32 | 41 | return flattened
|
|
0 commit comments