asyncapi-codegen icon indicating copy to clipboard operation
asyncapi-codegen copied to clipboard

Fix message payload type generation for allOf schema references

Open lmendes86 opened this issue 3 months ago • 1 comments

Fix message payload type generation for allOf schema references

Problem

Fixes #290

When generating Go code from AsyncAPI v2 specifications, message payloads that reference schemas using allOf composition were not generating proper type names. This resulted in compilation errors like:

type TestCreatedMessage struct {
    Payload // Missing type - compilation error!
}

The generated code would fail to compile with: undefined: Payload

Root Cause

The issue was in the schema-name.tmpl template logic. Message payloads with allOf composition had both .Type="object" and .Reference set. The template prioritized .Type over .Reference, attempting to use {{ namify .Name }} when .Name was empty, resulting in missing type names.

Solution

Reorganized the template logic in schema-name.tmpl to prioritize reference resolution:

  1. Reference handling first: .ReferenceTo and .Reference cases now precede .Type handling
  2. Preserved functionality: All existing cases (primitives, arrays, etc.) continue working
  3. Fixed the core issue: Message payloads with allOf references now resolve correctly

Changes

  • pkg/codegen/generators/v2/templates/schema_name.tmpl: Reordered conditional logic to prioritize references
  • pkg/asyncapi/v2/schema.go: Prevent name overwriting for schemas with references
  • pkg/codegen/generators/v2/templates/helpers.go: Added reference extraction helper (unchanged)

Testing

  • Added comprehensive test: test/v2/issues/290/ following project guidelines
  • Regression test: Confirms issue reproduction and fix validation
  • Before fix: Test fails with undefined: Payload compilation error
  • After fix: Generated code compiles successfully with proper types

Generated Code (After Fix)

  type TestCreatedMessage struct {
      // Payload will be inserted in the message payload
      Payload TestEventSchema  // Correct type from allOf reference
  }

lmendes86 avatar Sep 08 '25 14:09 lmendes86

Sorry about the delay, I had some changes in my life this 2 past months, I'll take a look ASAP.

lerenn avatar Oct 27 '25 09:10 lerenn