Skip to content

Commit

Permalink
openapi3gen: Fix issue with separate component generated for time.Time (
Browse files Browse the repository at this point in the history
#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 <max@mail.com>
  • Loading branch information
d1vbyz3r0 and mprytkov authored Feb 10, 2025
1 parent 72fb819 commit 050a930
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions openapi3gen/openapi3gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,11 @@ func (g *Generator) generateWithoutSaving(parents []*theTypeInfo, t reflect.Type

// For structs we add the schemas to the component schemas
if len(parents) > 1 || g.opts.exportComponentSchemas.ExportTopLevelSchema {
// If struct is a time.Time instance, separate component shouldn't be generated
if t == timeType {
return openapi3.NewSchemaRef(t.Name(), schema), nil
}

typeName := g.generateTypeName(t)

g.componentSchemaRefs[typeName] = struct{}{}
Expand Down
26 changes: 26 additions & 0 deletions openapi3gen/openapi3gen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/stretchr/testify/assert"
"reflect"
"strconv"
"strings"
Expand Down Expand Up @@ -641,3 +642,28 @@ func ExampleSetSchemar() {
// "type": "object"
// }
}

func TestExportComponentSchemasForTimeProp(t *testing.T) {
type Some struct {
Name string
CreatedAt time.Time
}

schemas := make(openapi3.Schemas)
g := openapi3gen.NewGenerator(
openapi3gen.UseAllExportedFields(),
openapi3gen.CreateComponentSchemas(openapi3gen.ExportComponentSchemasOptions{
ExportComponentSchemas: true,
}),
)

ref, err := g.NewSchemaRefForValue(&Some{}, schemas)
require.NoError(t, err)

schema, err := json.MarshalIndent(ref, "", " ")
require.NoError(t, err)

assert.Condition(t, func() bool {
return !strings.Contains(string(schema), "#/components/schemas/Time")
}, "Expected no schema for time.Time property but got one: %s", schema)
}

0 comments on commit 050a930

Please sign in to comment.