Skip to content

Unusable code for schema response with oneOf #1900

Description

@aBMania

Hello, I've looked for duplicate, but could not find exactly the same bug (as far as I searched), here are related ones:

And a related PR:

Steps to reproduce:

I've created minimal reproduction code here

1. OpenAPI Spec

openapi: 3.0.2
info:
  version: 1.0.0
  title: Issue 1900
paths:
  /ping:
    get:
      responses:
        '200':
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Pong1'
                  - $ref: '#/components/schemas/Pong2'
                  - $ref: '#/components/schemas/Pong3'

2. Oapi-codegen config

package: issue1900
output: ping.gen.go
generate:
  models: true
  client: true

3. Generated code

type GetPingResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		union json.RawMessage
	}
	JSON404 *Error
}

Here the JSON200 type is unusable

Workaround

As a workaround, I've manually modified the OpenAPI spec of the API we are using before generating code:

# Changed:
'/Ping':
  get:
    # ...
    responses:
      '200':
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PongResponse"

# Added: 
  schemas:
    # ...
    PongResponse:
      oneOf:
        - $ref: "#/components/schemas/Pong1"
        - $ref: "#/components/schemas/Pong2"
        - $ref: "#/components/schemas/Pong3"
    # ...

And it's now generating a usable type:

type GetPingResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *PongResponse  // generated type here
	JSON404      *Error
}
func (t PongResponse) AsPong1() (Pong1, error) { ... }
func (t PongResponse) AsPong2() (Pong2, error) { ... }
// ...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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