Skip to content

Commit

Permalink
Detect if a field is anonymous and handle the indirection (#386)
Browse files Browse the repository at this point in the history
  • Loading branch information
DerekStrickland authored Jul 29, 2021
1 parent bde5325 commit 7ee1637
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
18 changes: 15 additions & 3 deletions openapi3gen/openapi3gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,21 @@ func (g *Generator) generateWithoutSaving(parents []*jsoninfo.TypeInfo, t reflec
// If asked, try to use yaml tag
name, fType := fieldInfo.JSONName, fieldInfo.Type
if !fieldInfo.HasJSONTag && g.opts.useAllExportedFields {
ff := t.Field(fieldInfo.Index[len(fieldInfo.Index)-1])
if tag, ok := ff.Tag.Lookup("yaml"); ok && tag != "-" {
name, fType = tag, ff.Type
// Handle anonymous fields/embedded structs
if t.Field(fieldInfo.Index[0]).Anonymous {
ref, err := g.generateSchemaRefFor(parents, fType)
if err != nil {
return nil, err
}
if ref != nil {
g.SchemaRefs[ref]++
schema.WithPropertyRef(name, ref)
}
} else {
ff := t.Field(fieldInfo.Index[len(fieldInfo.Index)-1])
if tag, ok := ff.Tag.Lookup("yaml"); ok && tag != "-" {
name, fType = tag, ff.Type
}
}
}

Expand Down
31 changes: 31 additions & 0 deletions openapi3gen/openapi3gen_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package openapi3gen

import (
"reflect"
"testing"

"github.com/getkin/kin-openapi/openapi3"
Expand Down Expand Up @@ -53,3 +54,33 @@ func TestExportUint(t *testing.T) {
"uint": {Value: &openapi3.Schema{Type: "integer", Min: &zeroInt}},
}}}, schemaRef)
}

func TestEmbeddedStructs(t *testing.T) {
type EmbeddedStruct struct {
ID string
}

type ContainerStruct struct {
Name string
EmbeddedStruct
}

instance := &ContainerStruct{
Name: "Container",
EmbeddedStruct: EmbeddedStruct{
ID: "Embedded",
},
}

generator := NewGenerator(UseAllExportedFields())

schemaRef, err := generator.GenerateSchemaRef(reflect.TypeOf(instance))
require.NoError(t, err)

var ok bool
_, ok = schemaRef.Value.Properties["Name"]
require.Equal(t, true, ok)

_, ok = schemaRef.Value.Properties["ID"]
require.Equal(t, true, ok)
}

0 comments on commit 7ee1637

Please sign in to comment.