Skip to content
Open
Changes from 2 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
27 changes: 25 additions & 2 deletions reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ type Reflector struct {
// switching to just allowing additional properties instead.
IgnoredTypes []any

// Ignore specific struct field, enable dynamic generate different schemas from on struct.
Ignore func(reflect.StructField) bool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its not clear how this should be used... as a rule, I'd try to avoid using reflect types directly.


// Lookup allows a function to be defined that will provide a custom mapping of
// types to Schema IDs. This allows existing schema documents to be referenced
// by their ID instead of being embedded into the current schema definitions.
Expand Down Expand Up @@ -492,6 +495,10 @@ func (r *Reflector) reflectStructFields(st *Schema, definitions Definitions, t r
}

handleField := func(f reflect.StructField) {
if !f.Anonymous && r.Ignore != nil && r.Ignore(f) {
return
}

name, shouldEmbed, required, nullable := r.reflectFieldName(f)
// if anonymous and exported type should be processed recursively
// current type should inherit properties of anonymous one
Expand Down Expand Up @@ -1081,6 +1088,11 @@ func (t *Schema) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, aux)
}

// If true, marshal json with linebreak and indent.
var MarshalWithIndent = false
var MarshalPrefix = ""
var MarshalIndent = "\t"
Comment on lines +1097 to +1099

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Global variables should be avoided. Wouldn't you want to do this with the regular json.MarshalIndent method directly?


// MarshalJSON is used to serialize a schema object or boolean.
func (t *Schema) MarshalJSON() ([]byte, error) {
if t.boolean != nil {
Expand All @@ -1094,14 +1106,25 @@ func (t *Schema) MarshalJSON() ([]byte, error) {
return []byte("true"), nil
}
type SchemaAlt Schema
b, err := json.Marshal((*SchemaAlt)(t))
var b []byte
var err error
if MarshalWithIndent {
b, err = json.MarshalIndent((*SchemaAlt)(t), MarshalPrefix, MarshalIndent)
} else {
b, err = json.Marshal((*SchemaAlt)(t))
}
if err != nil {
return nil, err
}
if t.Extras == nil || len(t.Extras) == 0 {
return b, nil
}
m, err := json.Marshal(t.Extras)
var m []byte
if MarshalWithIndent {
m, err = json.MarshalIndent(t.Extras, MarshalPrefix, MarshalIndent)
} else {
m, err = json.Marshal(t.Extras)
}
if err != nil {
return nil, err
}
Expand Down