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

Polymorphism & Discriminator

Open adrianiacobghiula opened this issue 8 months ago • 2 comments

In the context of Polymorphism there are cases where the discriminator could have multiple values pointing to the same object

    CommunicationChannel:
      type: object
      oneOf:
      - $ref: '#/components/schemas/Phone'
      - $ref: '#/components/schemas/Email'
      - $ref: '#/components/schemas/PostAddress'
      discriminator:
        propertyName: type
        mapping:
          CALL: '#/components/schemas/Phone'
          SMS: '#/components/schemas/Phone'
          EMAIL: '#/components/schemas/Email'
          POST: '#/components/schemas/PostAddress'

as the generated code ignores one of the discriminators CALL or SMS because the generated functions are called based on the object (FromPhone) and not on the discriminators

// FromPhone overwrites any union data inside the CommunicationChannel as the provided Phone
func (t *CommunicationChannel) FromPhone(v Phone) error {
	v.Type = "SMS"
	b, err := json.Marshal(v)
	t.union = b
	return err
}

The only work around I found is to create 2 new objects

    CommunicationChannel:
      type: object
      oneOf:
      - $ref: '#/components/schemas/CallPhone'
      - $ref: '#/components/schemas/SmsPhone'
      - $ref: '#/components/schemas/Email'
      - $ref: '#/components/schemas/PostAddress'
      discriminator:
        propertyName: type
        mapping:
          CALL: '#/components/schemas/CallPhone'
          SMS: '#/components/schemas/SmsPhone'
          EMAIL: '#/components/schemas/Email'
          POST: '#/components/schemas/PostAddress'
    CallPhone:
      allOf:
        - $ref: '#/components/schemas/Phone'
    SmsPhone:
      allOf:
        - $ref: '#/components/schemas/Phone'

adrianiacobghiula avatar Jun 19 '24 04:06 adrianiacobghiula