Skip to content

Generate a type for nested struct in respond instead of anonymous struct #1139

@illiafox

Description

@illiafox

1. What version are you using?

❯ oapi-codegen --version
github.com/deepmap/oapi-codegen/cmd/oapi-codegen
v1.13.0

2. OpenAPI 3 spec:

  /roles/{id}:
    summary: Get role by id
    get:
      tags: [ role ]
      parameters:
        - name: id
          in: path
          description: Role ID
          required: true
          deprecated: false
          allowEmptyValue: false
          schema:
            type: integer
      responses:
        '200':
          description: Role
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Successful-Response'
                  - properties:
                      data:
                        type: object
                        properties:
                          role:
                            $ref: '#/components/schemas/Role'
                        required: [ role ]
   
components:
  schemas:
    Successful-Response:
      type: object
      properties:
        ok:
          type: boolean
          default: true
          description: Indicated whether the response is successful.
        data:
          type: object
          description: If successful, response from api
      required:
        - ok
        - data                     

3. Cmd arguments

oapi-codegen -config oapi.yaml -package api swagger.yaml

4. oapi-codegen config

package: api
generate:
  models: true
  fiber-server: true
  strict-server: true
  embedded-spec: true
output: api.gen.go

5. Expected behavior

type GetRolesId200JSONResponseData struct {
	Role Role `json:"role"`
}

type GetRolesId200JSONResponse struct {
	Data GetRolesId200JSONResponseData `json:"data"`

	// Ok Indicated whether the response is successful.
	Ok bool `json:"ok"`
}

6. Actual behavior

type GetRolesId200JSONResponse struct {
	Data struct {
		Role Role `json:"role"`
	} `json:"data"`

	// Ok Indicated whether the response is successful.
	Ok bool `json:"ok"`
}

With actual behavior there are only two ways to set data:

var resp api.GetRolesId200JSONResponse
resp.Ok = true
resp.Data.Role = role
resp = api.GetRolesId200JSONResponse{
	Ok: true,
	Data: struct {
		Role api.Role `json:"role"`
	}{
		Role: dto.Role(role),
	},
}

But I want to do like this

resp = api.GetRolesId200JSONResponse{
	Ok: true,
	Data: api.GetRolesId200JSONResponseData{
		Role: dto.Role(role),
	},
}

I saw issues and some fixes, but they don't seem to solve my problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions