Skip to content

Commit

Permalink
pkg/openapi: support basic validation via struct tags
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmdm committed Nov 24, 2024
1 parent 5234d6a commit ec9c794
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 5 deletions.
66 changes: 65 additions & 1 deletion pkg/openapi/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -97,7 +98,70 @@ func generateSchema(typ reflect.Type, top bool) *apiext.JSONSchemaProps {
schema.Required = append(schema.Required, key)
}

schema.Properties[key] = *generateSchema(f.Type, false)
fieldSchema := generateSchema(f.Type, false)
fieldValue := reflect.ValueOf(fieldSchema).Elem()

for _, name := range []string{
"Maximum",
"Minimum",
"MaxLength",
"MinLength",
"MaxItems",
"MinItems",
"UniqueItems",
// "Enum",
"Pattern",
"ExclusiveMaximum",
"ExclusiveMinimum",
"MultipleOf",
"Format",
} {
tag, ok := f.Tag.Lookup(name)
if !ok {
continue
}

fv := fieldValue.FieldByName(name)
ft := fv.Type()
if ft == nil {
continue
}

for ft.Kind() == reflect.Pointer {
if fv.IsNil() {
fv.Set(reflect.New(ft.Elem()))
}
fv = fv.Elem()
ft = ft.Elem()
}

// Limited type switch as these are the only types used for the above properties.
switch ft.Kind() {
case reflect.Int64:
val, err := strconv.ParseInt(tag, 0, ft.Bits())
if err != nil {
panic(fmt.Errorf("generate schema: property %q: %v", name, err))
}
fv.SetInt(val)
case reflect.Float64:
val, err := strconv.ParseFloat(tag, ft.Bits())
if err != nil {
panic(fmt.Errorf("generate schema: property %q: %v", name, err))
}
fv.SetFloat(val)
case reflect.Bool:
val, err := strconv.ParseBool(tag)
if err != nil {
panic(fmt.Errorf("generate schema: property %q: %v", name, err))
}
fv.SetBool(val)
case reflect.String:
fv.SetString(tag)
}

}

schema.Properties[key] = *fieldSchema
}

cache[typ] = schema
Expand Down
10 changes: 6 additions & 4 deletions pkg/openapi/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (

func TestGenerateSchema(t *testing.T) {
type S struct {
Name string `json:"name"`
Age int `json:"age"`
Name string `json:"name" MinLength:"3"`
Age int `json:"age" Minimum:"18"`
Labels map[string]string `json:"labels,omitempty"`
Active bool `json:"active"`
}
Expand All @@ -23,10 +23,12 @@ func TestGenerateSchema(t *testing.T) {
Type: "object",
Properties: apiext.JSONSchemaDefinitions{
"name": apiext.JSONSchemaProps{
Type: "string",
Type: "string",
MinLength: ptr[int64](3),
},
"age": apiext.JSONSchemaProps{
Type: "integer",
Type: "integer",
Minimum: ptr[float64](18),
},
"active": apiext.JSONSchemaProps{
Type: "boolean",
Expand Down

0 comments on commit ec9c794

Please sign in to comment.