Skip to content

Commit 7ee1637

Browse files
Detect if a field is anonymous and handle the indirection (#386)
1 parent bde5325 commit 7ee1637

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

openapi3gen/openapi3gen.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,21 @@ func (g *Generator) generateWithoutSaving(parents []*jsoninfo.TypeInfo, t reflec
217217
// If asked, try to use yaml tag
218218
name, fType := fieldInfo.JSONName, fieldInfo.Type
219219
if !fieldInfo.HasJSONTag && g.opts.useAllExportedFields {
220-
ff := t.Field(fieldInfo.Index[len(fieldInfo.Index)-1])
221-
if tag, ok := ff.Tag.Lookup("yaml"); ok && tag != "-" {
222-
name, fType = tag, ff.Type
220+
// Handle anonymous fields/embedded structs
221+
if t.Field(fieldInfo.Index[0]).Anonymous {
222+
ref, err := g.generateSchemaRefFor(parents, fType)
223+
if err != nil {
224+
return nil, err
225+
}
226+
if ref != nil {
227+
g.SchemaRefs[ref]++
228+
schema.WithPropertyRef(name, ref)
229+
}
230+
} else {
231+
ff := t.Field(fieldInfo.Index[len(fieldInfo.Index)-1])
232+
if tag, ok := ff.Tag.Lookup("yaml"); ok && tag != "-" {
233+
name, fType = tag, ff.Type
234+
}
223235
}
224236
}
225237

openapi3gen/openapi3gen_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package openapi3gen
22

33
import (
4+
"reflect"
45
"testing"
56

67
"github.com/getkin/kin-openapi/openapi3"
@@ -53,3 +54,33 @@ func TestExportUint(t *testing.T) {
5354
"uint": {Value: &openapi3.Schema{Type: "integer", Min: &zeroInt}},
5455
}}}, schemaRef)
5556
}
57+
58+
func TestEmbeddedStructs(t *testing.T) {
59+
type EmbeddedStruct struct {
60+
ID string
61+
}
62+
63+
type ContainerStruct struct {
64+
Name string
65+
EmbeddedStruct
66+
}
67+
68+
instance := &ContainerStruct{
69+
Name: "Container",
70+
EmbeddedStruct: EmbeddedStruct{
71+
ID: "Embedded",
72+
},
73+
}
74+
75+
generator := NewGenerator(UseAllExportedFields())
76+
77+
schemaRef, err := generator.GenerateSchemaRef(reflect.TypeOf(instance))
78+
require.NoError(t, err)
79+
80+
var ok bool
81+
_, ok = schemaRef.Value.Properties["Name"]
82+
require.Equal(t, true, ok)
83+
84+
_, ok = schemaRef.Value.Properties["ID"]
85+
require.Equal(t, true, ok)
86+
}

0 commit comments

Comments
 (0)