Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

openapi3gen: Fix issue with separate component generated for time.Time #1052

Merged
merged 2 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading