From dfe5549354a69fd7b79b3e3e508ec680d82f2c6b Mon Sep 17 00:00:00 2001 From: Louis FRADIN Date: Fri, 9 Oct 2026 18:47:44 +0200 Subject: [PATCH 1/2] feat(v3): generate enum types and constants (#337) Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 + .../generators/v3/templates/helpers.go | 85 ++++++++++ .../v3/templates/schema_definition.tmpl | 16 ++ .../generators/v3/templates/schema_name.tmpl | 4 +- test/v3/issues/131/asyncapi.gen.go | 28 +++- test/v3/issues/131/suite_test.go | 6 +- test/v3/issues/137/asyncapi.gen.go | 13 ++ test/v3/issues/224/asyncapi.gen.go | 16 +- test/v3/issues/245/asyncapi.gen.go | 26 ++- test/v3/issues/245/suite_test.go | 4 +- test/v3/issues/267/asyncapi.gen.go | 12 +- test/v3/issues/333/asyncapi.gen.go | 24 ++- test/v3/issues/337/asyncapi.gen.go | 154 ++++++++++++++++++ test/v3/issues/337/asyncapi.yaml | 44 +++++ test/v3/issues/337/suite_test.go | 26 +++ 15 files changed, 433 insertions(+), 30 deletions(-) create mode 100644 test/v3/issues/337/asyncapi.gen.go create mode 100644 test/v3/issues/337/asyncapi.yaml create mode 100644 test/v3/issues/337/suite_test.go diff --git a/README.md b/README.md index 4cba2bba..098f489f 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/pkg/codegen/generators/v3/templates/helpers.go b/pkg/codegen/generators/v3/templates/helpers.go index e5742aa3..e52f0dc0 100644 --- a/pkg/codegen/generators/v3/templates/helpers.go +++ b/pkg/codegen/generators/v3/templates/helpers.go @@ -3,6 +3,7 @@ package templates import ( "fmt" "regexp" + "sort" "strconv" "strings" "text/template" @@ -102,6 +103,9 @@ func DefaultLiteral(s *asyncapi.Schema) string { return strconv.FormatBool(b) case "string": 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" @@ -135,6 +139,83 @@ func formatDefaultNumber(v any) 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 != "string" || 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 { @@ -261,6 +342,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, diff --git a/pkg/codegen/generators/v3/templates/schema_definition.tmpl b/pkg/codegen/generators/v3/templates/schema_definition.tmpl index a4b5459e..d514ea05 100644 --- a/pkg/codegen/generators/v3/templates/schema_definition.tmpl +++ b/pkg/codegen/generators/v3/templates/schema_definition.tmpl @@ -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" .}} @@ -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 -}} diff --git a/pkg/codegen/generators/v3/templates/schema_name.tmpl b/pkg/codegen/generators/v3/templates/schema_name.tmpl index 4377ef85..3258ca8a 100644 --- a/pkg/codegen/generators/v3/templates/schema_name.tmpl +++ b/pkg/codegen/generators/v3/templates/schema_name.tmpl @@ -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 diff --git a/test/v3/issues/131/asyncapi.gen.go b/test/v3/issues/131/asyncapi.gen.go index 5f62c874..7b37ce1a 100644 --- a/test/v3/issues/131/asyncapi.gen.go +++ b/test/v3/issues/131/asyncapi.gen.go @@ -508,16 +508,28 @@ func (msg TestMessageFromTestChannel) toBrokerMessage() (extensions.BrokerMessag // TestSchema is a schema from the AsyncAPI specification required in messages type TestSchema struct { - ArrayProp []string `json:"ArrayProp,omitempty" validate:"omitempty,min=2,max=5,unique"` - ConstProp *string `json:"ConstProp,omitempty" validate:"omitempty,eq=Canada"` - EnumProp *string `json:"EnumProp,omitempty" validate:"omitempty,oneof='red' 'amber' 'green'"` - FloatProp *float64 `json:"FloatProp,omitempty" validate:"omitempty,gte=2.5,lte=5.5"` - IntegerExclusiveProp *int64 `json:"IntegerExclusiveProp,omitempty" validate:"omitempty,gt=2,lt=5"` - IntegerProp *int64 `json:"IntegerProp,omitempty" validate:"omitempty,gte=2,lte=5"` - RequiredProp string `json:"RequiredProp"` - StringProp *string `json:"StringProp,omitempty" validate:"omitempty,min=2,max=5"` + ArrayProp []string `json:"ArrayProp,omitempty" validate:"omitempty,min=2,max=5,unique"` + ConstProp *string `json:"ConstProp,omitempty" validate:"omitempty,eq=Canada"` + EnumProp *EnumPropPropertyFromTestSchema `json:"EnumProp,omitempty" validate:"omitempty,oneof='red' 'amber' 'green'"` + FloatProp *float64 `json:"FloatProp,omitempty" validate:"omitempty,gte=2.5,lte=5.5"` + IntegerExclusiveProp *int64 `json:"IntegerExclusiveProp,omitempty" validate:"omitempty,gt=2,lt=5"` + IntegerProp *int64 `json:"IntegerProp,omitempty" validate:"omitempty,gte=2,lte=5"` + RequiredProp string `json:"RequiredProp"` + StringProp *string `json:"StringProp,omitempty" validate:"omitempty,min=2,max=5"` } +// EnumPropPropertyFromTestSchema is a schema from the AsyncAPI specification required in messages +type EnumPropPropertyFromTestSchema string + +const ( + // EnumPropPropertyFromTestSchemaRed is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaRed EnumPropPropertyFromTestSchema = "red" + // EnumPropPropertyFromTestSchemaAmber is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaAmber EnumPropPropertyFromTestSchema = "amber" + // EnumPropPropertyFromTestSchemaGreen is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaGreen EnumPropPropertyFromTestSchema = "green" +) + const ( // TestChannelPath is the constant representing the 'TestChannel' channel path. TestChannelPath = "v3.issue131.test" diff --git a/test/v3/issues/131/suite_test.go b/test/v3/issues/131/suite_test.go index 6dbd6068..940e1e77 100644 --- a/test/v3/issues/131/suite_test.go +++ b/test/v3/issues/131/suite_test.go @@ -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"), } } @@ -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)) @@ -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)) diff --git a/test/v3/issues/137/asyncapi.gen.go b/test/v3/issues/137/asyncapi.gen.go index d6534d9f..375d5a71 100644 --- a/test/v3/issues/137/asyncapi.gen.go +++ b/test/v3/issues/137/asyncapi.gen.go @@ -35,3 +35,16 @@ type AuditSchema struct { // ChannelSchema is a schema from the AsyncAPI specification required in messages type ChannelSchema string + +const ( + // ChannelSchemaAPI0 is a possible value of ChannelSchema. + ChannelSchemaAPI0 ChannelSchema = "API0" + // ChannelSchemaAPI1 is a possible value of ChannelSchema. + ChannelSchemaAPI1 ChannelSchema = "API1" + // ChannelSchemaAPI2 is a possible value of ChannelSchema. + ChannelSchemaAPI2 ChannelSchema = "API2" + // ChannelSchemaAPI3 is a possible value of ChannelSchema. + ChannelSchemaAPI3 ChannelSchema = "API3" + // ChannelSchemaAPI4 is a possible value of ChannelSchema. + ChannelSchemaAPI4 ChannelSchema = "API4" +) diff --git a/test/v3/issues/224/asyncapi.gen.go b/test/v3/issues/224/asyncapi.gen.go index 0d7899f1..7d8d0381 100644 --- a/test/v3/issues/224/asyncapi.gen.go +++ b/test/v3/issues/224/asyncapi.gen.go @@ -524,8 +524,8 @@ func (t *ColliderSchema) SetDefaults() { // ShapePropertyFromColliderSchema is a schema from the AsyncAPI specification required in messages type ShapePropertyFromColliderSchema struct { - Radius float64 `json:"radius"` - ShapeType string `json:"shape_type" validate:"oneof='sphere'"` + Radius float64 `json:"radius"` + ShapeType ShapeTypePropertyFromSphereSchema `json:"shape_type" validate:"oneof='sphere'"` } // ColliderDictionarySchema is a schema from the AsyncAPI specification required in messages @@ -606,10 +606,18 @@ type PoseSchema struct { // SphereSchema is a schema from the AsyncAPI specification required in messages type SphereSchema struct { - Radius float64 `json:"radius"` - ShapeType string `json:"shape_type" validate:"oneof='sphere'"` + Radius float64 `json:"radius"` + ShapeType ShapeTypePropertyFromSphereSchema `json:"shape_type" validate:"oneof='sphere'"` } +// ShapeTypePropertyFromSphereSchema is a schema from the AsyncAPI specification required in messages +type ShapeTypePropertyFromSphereSchema string + +const ( + // ShapeTypePropertyFromSphereSchemaSphere is a possible value of ShapeTypePropertyFromSphereSchema. + ShapeTypePropertyFromSphereSchemaSphere ShapeTypePropertyFromSphereSchema = "sphere" +) + // Vector3dSchema is a schema from the AsyncAPI specification required in messages type Vector3dSchema []float64 diff --git a/test/v3/issues/245/asyncapi.gen.go b/test/v3/issues/245/asyncapi.gen.go index d9fae03f..b79e364d 100644 --- a/test/v3/issues/245/asyncapi.gen.go +++ b/test/v3/issues/245/asyncapi.gen.go @@ -508,15 +508,27 @@ func (msg TestMessageFromTestChannel) toBrokerMessage() (extensions.BrokerMessag // TestSchema is a schema from the AsyncAPI specification required in messages type TestSchema struct { - ArrayProp []string `json:"ArrayProp,omitempty" validate:"omitempty,min=2,max=5,unique"` - ConstProp *string `json:"ConstProp,omitempty" validate:"omitempty,eq=Canada"` - EnumProp *string `json:"EnumProp,omitempty" validate:"omitempty,oneof='red' 'amber' 'green'"` - FloatProp *float64 `json:"FloatProp,omitempty" validate:"omitempty,gte=2.5,lte=5.5"` - IntegerProp *int64 `json:"IntegerProp,omitempty" validate:"omitempty,gte=2,lte=5"` - RequiredProp string `json:"RequiredProp"` - StringProp *string `json:"StringProp,omitempty" validate:"omitempty,min=2,max=5"` + ArrayProp []string `json:"ArrayProp,omitempty" validate:"omitempty,min=2,max=5,unique"` + ConstProp *string `json:"ConstProp,omitempty" validate:"omitempty,eq=Canada"` + EnumProp *EnumPropPropertyFromTestSchema `json:"EnumProp,omitempty" validate:"omitempty,oneof='red' 'amber' 'green'"` + FloatProp *float64 `json:"FloatProp,omitempty" validate:"omitempty,gte=2.5,lte=5.5"` + IntegerProp *int64 `json:"IntegerProp,omitempty" validate:"omitempty,gte=2,lte=5"` + RequiredProp string `json:"RequiredProp"` + StringProp *string `json:"StringProp,omitempty" validate:"omitempty,min=2,max=5"` } +// EnumPropPropertyFromTestSchema is a schema from the AsyncAPI specification required in messages +type EnumPropPropertyFromTestSchema string + +const ( + // EnumPropPropertyFromTestSchemaRed is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaRed EnumPropPropertyFromTestSchema = "red" + // EnumPropPropertyFromTestSchemaAmber is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaAmber EnumPropPropertyFromTestSchema = "amber" + // EnumPropPropertyFromTestSchemaGreen is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaGreen EnumPropPropertyFromTestSchema = "green" +) + const ( // TestChannelPath is the constant representing the 'TestChannel' channel path. TestChannelPath = "v3.issue245.test" diff --git a/test/v3/issues/245/suite_test.go b/test/v3/issues/245/suite_test.go index 9f9d0f95..62047c25 100644 --- a/test/v3/issues/245/suite_test.go +++ b/test/v3/issues/245/suite_test.go @@ -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"), } } @@ -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"}`, }, { diff --git a/test/v3/issues/267/asyncapi.gen.go b/test/v3/issues/267/asyncapi.gen.go index cd614b97..c9578e6f 100644 --- a/test/v3/issues/267/asyncapi.gen.go +++ b/test/v3/issues/267/asyncapi.gen.go @@ -508,9 +508,19 @@ func (msg TestMessageFromTestChannel) toBrokerMessage() (extensions.BrokerMessag // TestSchema is a schema from the AsyncAPI specification required in messages type TestSchema struct { - EnumProp string `json:"EnumProp" validate:"oneof='nospaces' 'has a space'"` + EnumProp EnumPropPropertyFromTestSchema `json:"EnumProp" validate:"oneof='nospaces' 'has a space'"` } +// EnumPropPropertyFromTestSchema is a schema from the AsyncAPI specification required in messages +type EnumPropPropertyFromTestSchema string + +const ( + // EnumPropPropertyFromTestSchemaNospaces is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaNospaces EnumPropPropertyFromTestSchema = "nospaces" + // EnumPropPropertyFromTestSchemaHasASpace is a possible value of EnumPropPropertyFromTestSchema. + EnumPropPropertyFromTestSchemaHasASpace EnumPropPropertyFromTestSchema = "has a space" +) + const ( // TestChannelPath is the constant representing the 'TestChannel' channel path. TestChannelPath = "v3.issue267.test" diff --git a/test/v3/issues/333/asyncapi.gen.go b/test/v3/issues/333/asyncapi.gen.go index 66cb30bc..7dc98e6c 100644 --- a/test/v3/issues/333/asyncapi.gen.go +++ b/test/v3/issues/333/asyncapi.gen.go @@ -674,10 +674,18 @@ func (e *Error) Error() string { // UserDeletedMessagePayload is a schema from the AsyncAPI specification required in messages type UserDeletedMessagePayload struct { - Event string `json:"event" validate:"oneof='user_deleted'"` - Id string `json:"id"` + Event EventPropertyFromUserDeletedMessagePayload `json:"event" validate:"oneof='user_deleted'"` + Id string `json:"id"` } +// EventPropertyFromUserDeletedMessagePayload is a schema from the AsyncAPI specification required in messages +type EventPropertyFromUserDeletedMessagePayload string + +const ( + // EventPropertyFromUserDeletedMessagePayloadUserDeleted is a possible value of EventPropertyFromUserDeletedMessagePayload. + EventPropertyFromUserDeletedMessagePayloadUserDeleted EventPropertyFromUserDeletedMessagePayload = "user_deleted" +) + // UserDeletedMessage is the message expected for 'UserDeletedMessage' channel. type UserDeletedMessage struct { // Payload will be inserted in the message payload @@ -727,10 +735,18 @@ func (msg UserDeletedMessage) toBrokerMessage() (extensions.BrokerMessage, error // UserSignedUpMessagePayload is a schema from the AsyncAPI specification required in messages type UserSignedUpMessagePayload struct { - Event string `json:"event" validate:"oneof='user_signed_up'"` - Id string `json:"id"` + Event EventPropertyFromUserSignedUpMessagePayload `json:"event" validate:"oneof='user_signed_up'"` + Id string `json:"id"` } +// EventPropertyFromUserSignedUpMessagePayload is a schema from the AsyncAPI specification required in messages +type EventPropertyFromUserSignedUpMessagePayload string + +const ( + // EventPropertyFromUserSignedUpMessagePayloadUserSignedUp is a possible value of EventPropertyFromUserSignedUpMessagePayload. + EventPropertyFromUserSignedUpMessagePayloadUserSignedUp EventPropertyFromUserSignedUpMessagePayload = "user_signed_up" +) + // UserSignedUpMessage is the message expected for 'UserSignedUpMessage' channel. type UserSignedUpMessage struct { // Payload will be inserted in the message payload diff --git a/test/v3/issues/337/asyncapi.gen.go b/test/v3/issues/337/asyncapi.gen.go new file mode 100644 index 00000000..73704737 --- /dev/null +++ b/test/v3/issues/337/asyncapi.gen.go @@ -0,0 +1,154 @@ +// Package "issue337" provides primitives to interact with the AsyncAPI specification. +// +// Code generated by github.com/lerenn/asyncapi-codegen version (devel) DO NOT EDIT. +package issue337 + +import ( + "encoding/json" + "fmt" + + "github.com/lerenn/asyncapi-codegen/pkg/extensions" +) + +// AsyncAPIVersion is the version of the used AsyncAPI document +const AsyncAPIVersion = "1.0.0" + +// MessageWithCorrelationID is implemented by messages that carry a correlation ID. +type MessageWithCorrelationID interface { + CorrelationID() string + SetCorrelationID(id string) +} + +// Error is the error structure returned by the controller operations. +type Error struct { + Channel string + Err error +} + +// Error returns a string representation of the error. +func (e *Error) Error() string { + return fmt.Sprintf("channel %q: err %v", e.Channel, e.Err) +} + +// Message 'LightsMessageMessageFromLightsChannel' reference another one at '#/components/messages/lightsMessage'. +// This should be fixed in a future version to allow message override. +// If you encounter this message, feel free to open an issue on this subject +// to let know that you need this functionnality. + +// LightsMessageMessage is the message expected for 'LightsMessageMessage' channel. +type LightsMessageMessage struct { + // Payload will be inserted in the message payload + Payload FooSchema +} + +// NewLightsMessageMessage creates a new LightsMessageMessage with default values if any. +func NewLightsMessageMessage() LightsMessageMessage { + var msg LightsMessageMessage + + return msg +} + +// brokerMessageToLightsMessageMessage will fill a new LightsMessageMessage with data from generic broker message +func brokerMessageToLightsMessageMessage(bMsg extensions.BrokerMessage) (LightsMessageMessage, error) { + var msg LightsMessageMessage + + // Unmarshal payload to expected message payload format + err := json.Unmarshal(bMsg.Payload, &msg.Payload) + if err != nil { + return msg, err + } + + // TODO: run checks on msg type + + return msg, nil +} + +// toBrokerMessage will generate a generic broker message from LightsMessageMessage data +func (msg LightsMessageMessage) toBrokerMessage() (extensions.BrokerMessage, error) { + // TODO: implement checks on message + + // Marshal payload to JSON + payload, err := json.Marshal(msg.Payload) + if err != nil { + return extensions.BrokerMessage{}, err + } + + // There is no headers here + headers := make(map[string][]byte, 0) + + return extensions.BrokerMessage{ + Headers: headers, + Payload: payload, + }, nil +} + +// ColorSchema is a schema from the AsyncAPI specification required in messages +type ColorSchema string + +const ( + // ColorSchemaRed is a possible value of ColorSchema. + ColorSchemaRed ColorSchema = "red" + // ColorSchemaAmber is a possible value of ColorSchema. + ColorSchemaAmber ColorSchema = "amber" + // ColorSchemaGreen is a possible value of ColorSchema. + ColorSchemaGreen ColorSchema = "green" +) + +// FooSchema is a schema from the AsyncAPI specification required in messages +type FooSchema struct { + Color *ColorSchema `json:"color,omitempty" validate:"omitempty,oneof='red' 'amber' 'green'"` + Inline *InlinePropertyFromFooSchema `json:"inline,omitempty" validate:"omitempty,oneof='on' 'off' 'not-available'"` + InlineDefault *InlineDefaultPropertyFromFooSchema `json:"inlineDefault,omitempty" validate:"omitempty,oneof='low' 'high'"` + List []ItemFromListPropertyFromFooSchema `json:"list,omitempty"` +} + +// SetDefaults sets the default values defined in the AsyncAPI specification for +// the optional fields that are not set. +func (t *FooSchema) SetDefaults() { + if t.InlineDefault == nil { + v := InlineDefaultPropertyFromFooSchema("low") + t.InlineDefault = &v + } +} + +// InlineDefaultPropertyFromFooSchema is a schema from the AsyncAPI specification required in messages +type InlineDefaultPropertyFromFooSchema string + +const ( + // InlineDefaultPropertyFromFooSchemaLow is a possible value of InlineDefaultPropertyFromFooSchema. + InlineDefaultPropertyFromFooSchemaLow InlineDefaultPropertyFromFooSchema = "low" + // InlineDefaultPropertyFromFooSchemaHigh is a possible value of InlineDefaultPropertyFromFooSchema. + InlineDefaultPropertyFromFooSchemaHigh InlineDefaultPropertyFromFooSchema = "high" +) + +// InlinePropertyFromFooSchema is a schema from the AsyncAPI specification required in messages +type InlinePropertyFromFooSchema string + +const ( + // InlinePropertyFromFooSchemaOn is a possible value of InlinePropertyFromFooSchema. + InlinePropertyFromFooSchemaOn InlinePropertyFromFooSchema = "on" + // InlinePropertyFromFooSchemaOff is a possible value of InlinePropertyFromFooSchema. + InlinePropertyFromFooSchemaOff InlinePropertyFromFooSchema = "off" + // InlinePropertyFromFooSchemaNotAvailable is a possible value of InlinePropertyFromFooSchema. + InlinePropertyFromFooSchemaNotAvailable InlinePropertyFromFooSchema = "not-available" +) + +// ItemFromListPropertyFromFooSchema is a schema from the AsyncAPI specification required in messages +type ItemFromListPropertyFromFooSchema string + +const ( + // ItemFromListPropertyFromFooSchemaA is a possible value of ItemFromListPropertyFromFooSchema. + ItemFromListPropertyFromFooSchemaA ItemFromListPropertyFromFooSchema = "a" + // ItemFromListPropertyFromFooSchemaB is a possible value of ItemFromListPropertyFromFooSchema. + ItemFromListPropertyFromFooSchemaB ItemFromListPropertyFromFooSchema = "b" +) + +const ( + // LightsChannelPath is the constant representing the 'LightsChannel' channel path. + LightsChannelPath = "lights" +) + +// ChannelsPaths is an array of all channels paths +var ChannelsPaths = []string{ + LightsChannelPath, +} diff --git a/test/v3/issues/337/asyncapi.yaml b/test/v3/issues/337/asyncapi.yaml new file mode 100644 index 00000000..91f943cd --- /dev/null +++ b/test/v3/issues/337/asyncapi.yaml @@ -0,0 +1,44 @@ +asyncapi: 3.0.0 +info: + title: Enum values + version: 1.0.0 + +channels: + lights: + address: lights + messages: + lightsMessage: + $ref: '#/components/messages/lightsMessage' + +operations: + receiveLights: + action: receive + channel: + $ref: '#/channels/lights' + +components: + messages: + lightsMessage: + payload: + $ref: '#/components/schemas/Foo' + schemas: + Color: + type: string + enum: [red, amber, green] + Foo: + type: object + properties: + color: + $ref: '#/components/schemas/Color' + inline: + type: string + enum: ["on", "off", "not-available"] + inlineDefault: + type: string + enum: [low, high] + default: low + list: + type: array + items: + type: string + enum: [a, b] diff --git a/test/v3/issues/337/suite_test.go b/test/v3/issues/337/suite_test.go new file mode 100644 index 00000000..902ae50d --- /dev/null +++ b/test/v3/issues/337/suite_test.go @@ -0,0 +1,26 @@ +//go:generate go run ../../../../cmd/asyncapi-codegen -g types -p issue337 -i asyncapi.yaml -o ./asyncapi.gen.go +package issue337 + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestEnumValuesAreGenerated(t *testing.T) { + assert.Equal(t, ColorSchema("red"), ColorSchemaRed) + assert.Equal(t, ColorSchema("amber"), ColorSchemaAmber) + assert.Equal(t, ColorSchema("green"), ColorSchemaGreen) + + color := ColorSchemaGreen + foo := FooSchema{Color: &color} + assert.Equal(t, ColorSchemaGreen, *foo.Color) +} + +func TestInlineEnumValuesAreGenerated(t *testing.T) { + assert.Equal(t, "not-available", string(InlinePropertyFromFooSchemaNotAvailable)) + + foo := FooSchema{} + foo.SetDefaults() + assert.Equal(t, InlineDefaultPropertyFromFooSchema("low"), *foo.InlineDefault) +} From f8d8ef686e3bb21846f65ffc64a0f524656e936d Mon Sep 17 00:00:00 2001 From: Louis FRADIN Date: Fri, 9 Oct 2026 18:52:39 +0200 Subject: [PATCH 2/2] fix(lint): use a constant for the string schema type Co-Authored-By: Claude Sonnet 5.5 --- pkg/codegen/generators/v3/templates/helpers.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pkg/codegen/generators/v3/templates/helpers.go b/pkg/codegen/generators/v3/templates/helpers.go index e52f0dc0..69bdd1b8 100644 --- a/pkg/codegen/generators/v3/templates/helpers.go +++ b/pkg/codegen/generators/v3/templates/helpers.go @@ -84,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" @@ -101,7 +101,7 @@ 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)) @@ -139,12 +139,14 @@ 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 != "string" || len(s.Enum) == 0 || s.Name == "" || s.ExtGoType != "" { + if s == nil || s.Type != schemaTypeString || len(s.Enum) == 0 || s.Name == "" || s.ExtGoType != "" { return false } if s.Format == "date" || s.Format == "date-time" {