Skip to content

allOf with cross-file does not qualify nested type references from source schema #2288

@xiongzubiao

Description

@xiongzubiao

Description

When using allOf to extend a schema from another file, oapi-codegen flattens the fields correctly but does not qualify nested type references that originate from the source schema's file. This produces uncompilable Go code.

Reproduction

Given two OpenAPI spec files with an import-mapping configured:

api/common/openapi.yaml

openapi: 3.0.0
info:
  title: Common
  version: 0.1.0
paths: {}
components:
  schemas:
    Role:
      type: string
      enum: [admin, user]
    User:
      type: object
      required: [id, username]
      properties:
        id:
          type: string
        username:
          type: string
        roles:
          type: array
          items:
            $ref: '#/components/schemas/Role'

api/service/openapi.yaml

openapi: 3.0.0
info:
  title: Service
  version: 0.1.0
paths: {}
components:
  schemas:
    EnrichedUser:
      allOf:
      - $ref: '../common/openapi.yaml#/components/schemas/User'
      - type: object
        properties:
          extra_field:
            type: string

api/service/types.yaml (codegen config)

package: service
generate:
  models: true
output: types.gen.go
import-mapping:
  '../common/openapi.yaml': common github.com/example/api/common

Expected behavior

Generated EnrichedUser should qualify the Role reference via the import mapping:

type EnrichedUser struct {
    ExtraField *string        `json:"extra_field,omitempty"`
    ID         string         `json:"id"`
    Roles      *[]common.Role `json:"roles,omitempty"`
    Username   string         `json:"username"`
}

Actual behavior

Generated code uses an unqualified Role reference:

type EnrichedUser struct {
    ExtraField *string    `json:"extra_field,omitempty"`
    ID         string     `json:"id"`
    Roles      *[]Role    `json:"roles,omitempty"`  // <-- unqualified
    Username   string     `json:"username"`
}

This fails to compile: undefined: Role

Workaround

Override the field in the allOf extension with a direct cross-file $ref:

    EnrichedUser:
      allOf:
      - $ref: '../common/openapi.yaml#/components/schemas/User'
      - type: object
        properties:
          roles:
            type: array
            items:
              $ref: '../common/openapi.yaml#/components/schemas/Role'
          extra_field:
            type: string

This correctly generates Roles *[]common.Role.

Version

oapi-codegen v2.6.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions