Skip to content

Commit 050a930

Browse files
d1vbyz3r0mprytkov
and
mprytkov
authored
openapi3gen: Fix issue with separate component generated for time.Time (#1052)
* openapi3gen: Fix issue with separate component generated for time.Time fields, when ExportComponentSchemas opt provided * openapi3gen: Add tests for time.Time issue fix --------- Co-authored-by: mprytkov <[email protected]>
1 parent 72fb819 commit 050a930

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

openapi3gen/openapi3gen.go

+5
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,11 @@ func (g *Generator) generateWithoutSaving(parents []*theTypeInfo, t reflect.Type
429429

430430
// For structs we add the schemas to the component schemas
431431
if len(parents) > 1 || g.opts.exportComponentSchemas.ExportTopLevelSchema {
432+
// If struct is a time.Time instance, separate component shouldn't be generated
433+
if t == timeType {
434+
return openapi3.NewSchemaRef(t.Name(), schema), nil
435+
}
436+
432437
typeName := g.generateTypeName(t)
433438

434439
g.componentSchemaRefs[typeName] = struct{}{}

openapi3gen/openapi3gen_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7+
"github.com/stretchr/testify/assert"
78
"reflect"
89
"strconv"
910
"strings"
@@ -641,3 +642,28 @@ func ExampleSetSchemar() {
641642
// "type": "object"
642643
// }
643644
}
645+
646+
func TestExportComponentSchemasForTimeProp(t *testing.T) {
647+
type Some struct {
648+
Name string
649+
CreatedAt time.Time
650+
}
651+
652+
schemas := make(openapi3.Schemas)
653+
g := openapi3gen.NewGenerator(
654+
openapi3gen.UseAllExportedFields(),
655+
openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
656+
ExportComponentSchemas: true,
657+
}),
658+
)
659+
660+
ref, err := g.NewSchemaRefForValue(&Some{}, schemas)
661+
require.NoError(t, err)
662+
663+
schema, err := json.MarshalIndent(ref, "", " ")
664+
require.NoError(t, err)
665+
666+
assert.Condition(t, func() bool {
667+
return !strings.Contains(string(schema), "#/components/schemas/Time")
668+
}, "Expected no schema for time.Time property but got one: %s", schema)
669+
}

0 commit comments

Comments
 (0)