Skip to content
Open
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
44 changes: 40 additions & 4 deletions pkg/generator/schema_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@ func (g *schemaGenerator) generateDeclaredType(t *schemas.Type, scope nameScope)
return &codegen.NamedType{Decl: &decl}, nil
}

//nolint:gocyclo // todo: reduce cyclomatic complexity
func (g *schemaGenerator) structFieldValidators(
validators []validator,
f codegen.StructField,
Expand All @@ -393,12 +394,23 @@ func (g *schemaGenerator) structFieldValidators(
validators = g.structFieldValidators(validators, f, v.Type, v.IsNillable())

case codegen.PrimitiveType:
if v.Type == schemas.TypeNameString {
switch {
case v.Type == schemas.TypeNameString:
hasPattern := len(f.SchemaType.Pattern) != 0
if f.SchemaType.MinLength != 0 || f.SchemaType.MaxLength != 0 || hasPattern {
if f.SchemaType.MinLength != 0 || f.SchemaType.MaxLength != 0 || hasPattern || f.SchemaType.Const != nil {
// Double escape the escape characters so we don't effectively parse the escapes within the value.
escapedPattern := f.SchemaType.Pattern

var constVal *string

if f.SchemaType.Const != nil {
if s, ok := f.SchemaType.Const.(string); ok {
constVal = &s
} else {
g.warner(fmt.Sprintf("Ignoring non string const value: %v", f.SchemaType.Const))
}
}

replaceJSONCharactersBy := []string{"\\b", "\\f", "\\n", "\\r", "\\t"}

replaceJSONCharacters := []string{"\b", "\f", "\n", "\r", "\t"}
Expand All @@ -413,19 +425,22 @@ func (g *schemaGenerator) structFieldValidators(
minLength: f.SchemaType.MinLength,
maxLength: f.SchemaType.MaxLength,
pattern: escapedPattern,
constVal: constVal,
isNillable: isNillable,
})
}

if hasPattern {
g.output.file.Package.AddImport("regexp", "")
}
} else if strings.Contains(v.Type, "int") || v.Type == float64Type {

case strings.Contains(v.Type, "int") || v.Type == float64Type:
if f.SchemaType.MultipleOf != nil ||
f.SchemaType.Maximum != nil ||
f.SchemaType.ExclusiveMaximum != nil ||
f.SchemaType.Minimum != nil ||
f.SchemaType.ExclusiveMinimum != nil {
f.SchemaType.ExclusiveMinimum != nil ||
f.SchemaType.Const != nil {
validators = append(validators, &numericValidator{
jsonName: f.JSONName,
fieldName: f.Name,
Expand All @@ -435,13 +450,34 @@ func (g *schemaGenerator) structFieldValidators(
exclusiveMaximum: f.SchemaType.ExclusiveMaximum,
minimum: f.SchemaType.Minimum,
exclusiveMinimum: f.SchemaType.ExclusiveMinimum,
constVal: f.SchemaType.Const,
roundToInt: strings.Contains(v.Type, "int"),
})
}

if f.SchemaType.MultipleOf != nil && v.Type == float64Type {
g.output.file.Package.AddImport("math", "")
}

case v.Type == "bool":
if f.SchemaType.Const != nil {
var constVal *bool

if f.SchemaType.Const != nil {
if b, ok := f.SchemaType.Const.(bool); ok {
constVal = &b
} else {
g.warner(fmt.Sprintf("Ignoring non boolean const value: %v", f.SchemaType.Const))
}
}

validators = append(validators, &booleanValidator{
jsonName: f.JSONName,
fieldName: f.Name,
isNillable: isNillable,
constVal: constVal,
})
}
}

case *codegen.ArrayType:
Expand Down
54 changes: 54 additions & 0 deletions pkg/generator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ type stringValidator struct {
maxLength int
isNillable bool
pattern string
constVal *string
}

func (v *stringValidator) generate(out *codegen.Emitter, format string) error {
Expand Down Expand Up @@ -393,6 +394,14 @@ func (v *stringValidator) generate(out *codegen.Emitter, format string) error {
}
}

if v.constVal != nil {
out.Printlnf(`if %s%s%s != "%s" {`, checkPointer, pointerPrefix, value, *v.constVal)
out.Indent(1)
out.Printlnf(`return fmt.Errorf("field %%s: must be equal to %%s", "%s", "%s")`, fieldName, *v.constVal)
out.Indent(-1)
out.Printlnf("}")
}

if v.minLength == 0 && v.maxLength == 0 {
return nil
}
Expand Down Expand Up @@ -432,6 +441,7 @@ type numericValidator struct {
exclusiveMaximum *any
minimum *float64
exclusiveMinimum *any
constVal any
roundToInt bool
}

Expand All @@ -445,6 +455,14 @@ func (v *numericValidator) generate(out *codegen.Emitter, format string) error {
pointerPrefix = "*"
}

if v.constVal != nil {
out.Printlnf(`if %s%s%s != %v {`, checkPointer, pointerPrefix, value, v.constVal)
out.Indent(1)
out.Printlnf(`return fmt.Errorf("field %%s: must be equal to %%v", "%s", %v)`, v.jsonName, v.constVal)
out.Indent(-1)
out.Printlnf("}")
}

if v.multipleOf != nil {
if v.roundToInt {
out.Printlnf(`if %s %s%s %% %v != 0 {`, checkPointer, pointerPrefix, value, v.valueOf(*v.multipleOf))
Expand Down Expand Up @@ -527,6 +545,42 @@ func (v *numericValidator) valueOf(val float64) any {
return val
}

type booleanValidator struct {
jsonName string
fieldName string
isNillable bool
constVal *bool
}

func (v *booleanValidator) generate(out *codegen.Emitter, unmarshalTemplate string) error {
value := getPlainName(v.fieldName)
fieldName := v.jsonName
checkPointer := ""
pointerPrefix := ""

if v.isNillable {
checkPointer = fmt.Sprintf("%s != nil && ", value)
pointerPrefix = "*"
}

if v.constVal != nil {
out.Printlnf(`if %s%s%s != %t {`, checkPointer, pointerPrefix, value, *v.constVal)
out.Indent(1)
out.Printlnf(`return fmt.Errorf("field %%s: must be equal to %%t", "%s", %t)`, fieldName, *v.constVal)
out.Indent(-1)
out.Printlnf("}")
}

return nil
}

func (v *booleanValidator) desc() *validatorDesc {
return &validatorDesc{
hasError: true,
beforeJSONUnmarshal: false,
}
}

func getPlainName(fieldName string) string {
if fieldName == "" {
return varNamePlainStruct
Expand Down
1 change: 1 addition & 0 deletions pkg/schemas/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ type Type struct {
AdditionalProperties *Type `json:"additionalProperties,omitempty"` // Section 5.18.
Enum []interface{} `json:"enum,omitempty"` // Section 5.20.
Type TypeList `json:"type,omitempty"` // Section 5.21.
Const interface{} `json:"const,omitempty"`
// RFC draft-bhutton-json-schema-01, section 10.
AllOf []*Type `json:"allOf,omitempty"` // Section 10.2.1.1.
AnyOf []*Type `json:"anyOf,omitempty"` // Section 10.2.1.2.
Expand Down
159 changes: 159 additions & 0 deletions tests/data/core/const/const.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading