Skip to content
Merged
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,11 @@ The following tags are currently supported:
| uniqueItems | unique | Only for arrays |
| enum | oneof | Only string enum are supported |

String enums (component or inline) are also generated as a dedicated Go type with
one constant per value (e.g. `type Color string` with `ColorRed`, `ColorGreen`, ...)
for the v3 generator. Enums with `x-go-type` or a `date`/`date-time` format keep
their plain type.

You can validate manually wherever you hold a generated payload, or plug in the
provided opt-in middleware to reject invalid messages automatically:

Expand Down
91 changes: 89 additions & 2 deletions pkg/codegen/generators/v3/templates/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package templates
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
Expand Down Expand Up @@ -83,7 +84,7 @@ func HasScalarDefault(s *asyncapi.Schema) bool {
switch s.Type {
case "boolean", "integer", "number":
return true
case "string":
case schemaTypeString:
// Generated date/time types have a non-trivial literal form, so they
// are intentionally left out.
return s.Format != "date" && s.Format != "date-time"
Expand All @@ -100,8 +101,11 @@ func DefaultLiteral(s *asyncapi.Schema) string {
case "boolean":
b, _ := s.Default.(bool)
return strconv.FormatBool(b)
case "string":
case schemaTypeString:
str, _ := s.Default.(string)
if IsGeneratedEnum(s) {
return fmt.Sprintf("%s(%s)", templateutil.Namify(s.Name), strconv.Quote(str))
}
return strconv.Quote(str)
case "integer":
goType := "int64"
Expand Down Expand Up @@ -135,6 +139,85 @@ func formatDefaultNumber(v any) string {
}
}

const schemaTypeString = "string"

// IsGeneratedEnum reports whether the schema is a string enumeration for which a
// dedicated Go type and constants are generated (issue #337). Enumerations with
// a custom Go type, a generated date/time format or non-string values are left
// as their plain underlying type.
func IsGeneratedEnum(s *asyncapi.Schema) bool {
if s == nil || s.Type != schemaTypeString || len(s.Enum) == 0 || s.Name == "" || s.ExtGoType != "" {
return false
}
if s.Format == "date" || s.Format == "date-time" {
return false
}
for _, e := range s.Enum {
if _, ok := e.(string); !ok {
return false
}
}
return true
}

// EnumChildren returns the generated enumeration schemas that are direct
// children (properties, items, additional properties) of the given schema,
// sorted by name so the generated code is stable.
func EnumChildren(s *asyncapi.Schema) []*asyncapi.Schema {
// Each candidate is paired with the schema that names it. A schema can be
// shared between several parents (e.g. through a merged reference), so an
// enumeration is only generated by the parent it was named after, to avoid
// declaring the same type twice.
type candidate struct{ owner, schema *asyncapi.Schema }

candidates := []candidate{{s, s.Items}, {s, s.AdditionalProperties}}
for _, p := range s.Properties {
candidates = append(candidates, candidate{s, p})
if p.Type == "array" {
// Arrays of enumerations declared inline in a property.
candidates = append(candidates, candidate{p, p.Items})
}
}

children := make([]*asyncapi.Schema, 0, len(candidates))
seen := make(map[string]bool)
for _, c := range candidates {
if IsGeneratedEnum(c.schema) && strings.HasSuffix(c.schema.Name, "From"+c.owner.Name) && !seen[c.schema.Name] {
seen[c.schema.Name] = true
children = append(children, c.schema)
}
}
sort.Slice(children, func(i, j int) bool { return children[i].Name < children[j].Name })

return children
}

// EnumConstants returns the Go constant names of the enumeration values, in the
// order of the specification. Names are the type name followed by the namified
// value; empty or colliding names get the value index appended.
func EnumConstants(s *asyncapi.Schema) []string {
typeName := templateutil.Namify(s.Name)
names := make([]string, len(s.Enum))
used := make(map[string]bool, len(s.Enum))
for i, e := range s.Enum {
v, _ := e.(string)
name := typeName + templateutil.Namify(v)
if templateutil.Namify(v) == "" || used[name] {
name = fmt.Sprintf("%s%d", name, i)
}
used[name] = true
names[i] = name
}

return names
}

// EnumValue returns the quoted Go string literal of the i-th enumeration value.
func EnumValue(s *asyncapi.Schema, i int) string {
v, _ := s.Enum[i].(string)
return strconv.Quote(v)
}

// SubscribeFuncName returns the Go name of the SubscribeTo function generated
// for the given operation, honoring the x-go-subscribe-func override.
func SubscribeFuncName(op *asyncapi.Operation) string {
Expand Down Expand Up @@ -261,6 +344,10 @@ func HelpersFunctions() template.FuncMap {
"referenceToStructAttributePath": generators.ReferenceToStructAttributePath,
"generateValidateTags": generators.GenerateValidateTags[asyncapi.Schema],
"generateJSONTags": generators.GenerateJSONTags[asyncapi.Schema],
"isGeneratedEnum": IsGeneratedEnum,
"enumChildren": EnumChildren,
"enumConstants": EnumConstants,
"enumValue": EnumValue,
"hasScalarDefault": HasScalarDefault,
"defaultLiteral": DefaultLiteral,
"subscribeFuncName": SubscribeFuncName,
Expand Down
16 changes: 16 additions & 0 deletions pkg/codegen/generators/v3/templates/schema_definition.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ func (t *{{ namify .Name }}) SetDefaults() {
{{- end}}

{{- /* ----------------------------- Others ----------------------------- */ -}}
{{- else if isGeneratedEnum . -}}

type {{ namify .Name }} string

{{- $consts := enumConstants .}}

const (
{{- range $i, $c := $consts}}
// {{ $c }} is a possible value of {{ namify $.Name }}.
{{ $c }} {{ namify $.Name }} = {{ enumValue $ $i }}
{{- end}}
)

{{- else -}}

type {{ .Name }} {{template "schema-name" .}}
Expand All @@ -72,6 +85,9 @@ type {{ .Name }} {{template "schema-name" .}}
{{- range $key, $value := getChildrenObjectSchemas . }}
{{template "schema-definition" $value }}
{{- end}}
{{- range $value := enumChildren . }}
{{template "schema-definition" $value }}
{{- end}}
{{- end}}

{{- end -}}
4 changes: 3 additions & 1 deletion pkg/codegen/generators/v3/templates/schema_name.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ bool

{{- /* --------------------------- Type String -------------------------- */ -}}
{{- else if eq .Type "string" -}}
{{- if and (isDateOrDateTimeGenerated .Format) (eq .Format "date") -}}
{{- if isGeneratedEnum . -}}
{{ namify .Name }}
{{- else if and (isDateOrDateTimeGenerated .Format) (eq .Format "date") -}}
civil.Date
{{- else if and (isDateOrDateTimeGenerated .Format) (eq .Format "date-time") -}}
time.Time
Expand Down
28 changes: 20 additions & 8 deletions test/v3/issues/131/asyncapi.gen.go

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

6 changes: 3 additions & 3 deletions test/v3/issues/131/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func ValidTestSchema() TestSchema {
IntegerProp: Ptr[int64](2),
IntegerExclusiveProp: Ptr[int64](3),
FloatProp: Ptr[float64](2.55),
EnumProp: Ptr("amber"),
EnumProp: Ptr(EnumPropPropertyFromTestSchemaAmber),
ConstProp: Ptr("Canada"),
}
}
Expand Down Expand Up @@ -144,7 +144,7 @@ func (suite *Suite) TestArray() {

func (suite *Suite) TestEnum() {
wrong := ValidTestSchema()
wrong.EnumProp = Ptr("Wrong")
wrong.EnumProp = Ptr(EnumPropPropertyFromTestSchema("Wrong"))

assert.Error(suite.T(), validator.New().Struct(wrong))

Expand All @@ -156,7 +156,7 @@ func (suite *Suite) TestEnum() {

func (suite *Suite) TestConst() {
wrong := ValidTestSchema()
wrong.EnumProp = Ptr("Wrong")
wrong.EnumProp = Ptr(EnumPropPropertyFromTestSchema("Wrong"))

assert.Error(suite.T(), validator.New().Struct(wrong))

Expand Down
13 changes: 13 additions & 0 deletions test/v3/issues/137/asyncapi.gen.go

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

16 changes: 12 additions & 4 deletions test/v3/issues/224/asyncapi.gen.go

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

26 changes: 19 additions & 7 deletions test/v3/issues/245/asyncapi.gen.go

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

4 changes: 2 additions & 2 deletions test/v3/issues/245/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func ValidTestSchema() TestSchema {
ArrayProp: []string{"test1", "test2"},
IntegerProp: Ptr[int64](2),
FloatProp: Ptr[float64](2.55),
EnumProp: Ptr("amber"),
EnumProp: Ptr(EnumPropPropertyFromTestSchemaAmber),
ConstProp: Ptr("Canada"),
}
}
Expand Down Expand Up @@ -66,7 +66,7 @@ func (suite *Suite) TestGenerateJsonOmitEmptyTag() {
},
{
name: "EnumProp is not nil",
data: TestSchema{RequiredProp: "test", EnumProp: Ptr("amber")},
data: TestSchema{RequiredProp: "test", EnumProp: Ptr(EnumPropPropertyFromTestSchemaAmber)},
expected: `{"RequiredProp":"test", "EnumProp":"amber"}`,
},
{
Expand Down
12 changes: 11 additions & 1 deletion test/v3/issues/267/asyncapi.gen.go

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

Loading
Loading