Skip to content

Commit 04f6ad4

Browse files
committed
Add ExcludeSchema sentinel error for schemaCustomizer
1 parent 8287d36 commit 04f6ad4

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

openapi3gen/openapi3gen.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,22 @@ type CycleError struct{}
1818

1919
func (err *CycleError) Error() string { return "detected cycle" }
2020

21+
// ExcludeSchema indicates that the schema for a specific field should not be included in the final output.
22+
type ExcludeSchmea struct{}
23+
24+
func (err *ExcludeSchmea) Error() string { return "schema excluded" }
25+
2126
// Option allows tweaking SchemaRef generation
2227
type Option func(*generatorOpt)
2328

2429
// SchemaCustomizerFn is a callback function, allowing
2530
// the OpenAPI schema definition to be updated with additional
2631
// properties during the generation process, based on the
2732
// name of the field, the Go type, and the struct tags.
28-
// name will be "_root" for the top level object, and tag will be ""
33+
// name will be "_root" for the top level object, and tag will be "".
34+
// A SchemaCustomizerFn can return an ExcludeSchmea sentinel error to
35+
// indicate that the schema for this field should not be included in
36+
// the final output
2937
type SchemaCustomizerFn func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error
3038

3139
type generatorOpt struct {
@@ -117,6 +125,10 @@ func (g *Generator) generateSchemaRefFor(parents []*jsoninfo.TypeInfo, t reflect
117125
return ref, nil
118126
}
119127
ref, err := g.generateWithoutSaving(parents, t, name, tag)
128+
if _, ok := err.(*ExcludeSchmea); ok {
129+
// This schema should not be included in the final output
130+
return nil, nil
131+
}
120132
if err != nil {
121133
return nil, err
122134
}

openapi3gen/openapi3gen_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,17 @@ func TestSchemaCustomizerError(t *testing.T) {
468468
require.EqualError(t, err, "test error")
469469
}
470470

471+
func TestSchemaCustomizerExcludeSchema(t *testing.T) {
472+
customizer := openapi3gen.SchemaCustomizer(func(name string, ft reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error {
473+
return &openapi3gen.ExcludeSchmea{}
474+
})
475+
476+
type Bla struct{}
477+
schema, err := openapi3gen.NewSchemaRefForValue(&Bla{}, nil, openapi3gen.UseAllExportedFields(), customizer)
478+
require.NoError(t, err)
479+
require.Nil(t, schema)
480+
}
481+
471482
func ExampleNewSchemaRefForValue_recursive() {
472483
type RecursiveType struct {
473484
Field1 string `json:"field1"`

0 commit comments

Comments
 (0)