tuning example rendering

This commit is contained in:
quobix
2024-05-01 12:59:15 -04:00
parent 2464753173
commit 7f945e35c4

View File

@@ -139,8 +139,24 @@ func (wr *SchemaRenderer) DiveIntoSchema(schema *base.Schema, key string, struct
maxLength = *schema.MaxLength maxLength = *schema.MaxLength
} }
// if there are examples, use them.
if schema.Examples != nil && len(schema.Examples) > 0 { if schema.Examples != nil && len(schema.Examples) > 0 {
var renderedExample any var renderedExample any
// multi examples and the type is an array? then render all examples.
if len(schema.Examples) > 1 && key == itemsType {
renderedExamples := make([]any, len(schema.Examples))
for i, exmp := range schema.Examples {
if exmp != nil {
var ex any
_ = exmp.Decode(&ex)
renderedExamples[i] = fmt.Sprint(ex)
}
}
structure[key] = renderedExamples
return
} else {
// render the first example
exmp := schema.Examples[0] exmp := schema.Examples[0]
if exmp != nil { if exmp != nil {
var ex any var ex any
@@ -150,6 +166,7 @@ func (wr *SchemaRenderer) DiveIntoSchema(schema *base.Schema, key string, struct
structure[key] = renderedExample structure[key] = renderedExample
return return
} }
}
switch schema.Format { switch schema.Format {
case dateTimeType: case dateTimeType:
@@ -198,30 +215,6 @@ func (wr *SchemaRenderer) DiveIntoSchema(schema *base.Schema, key string, struct
structure[key] = str structure[key] = str
} }
} else { } else {
if key == itemsType {
// check if the schema contains an example
if schema.Example != nil {
var example any
_ = schema.Example.Decode(&example)
structure[key] = fmt.Sprint(example)
return
}
// if the schema contains examples, then render them.
if schema.Examples != nil {
if len(schema.Examples) > 0 {
renderedExamples := make([]any, len(schema.Examples))
for i, exmp := range schema.Examples {
if exmp != nil {
var ex any
_ = exmp.Decode(&ex)
renderedExamples[i] = fmt.Sprint(ex)
}
}
structure[key] = renderedExamples
return
}
}
}
// last resort, generate a random value // last resort, generate a random value
structure[key] = wr.RandomWord(minLength, maxLength, 0) structure[key] = wr.RandomWord(minLength, maxLength, 0)
} }