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

Allow Struct Embedding with `allOf`

Open clarkjohnd opened this issue 4 months ago • 2 comments

A rebase of 2 year old PR (https://github.com/oapi-codegen/oapi-codegen/pull/1295) (main code courtesy of Lahabana!) to the latest main branch with a very small tweak to error handling. This is a feature I find very useful. Also addresses https://github.com/oapi-codegen/oapi-codegen/issues/1622#issue-2310736019, where the original draft PR was linked.

Using one of my own app examples, adding x-go-allof-embed-refs: true to allOf components:

    WorkItemView:
      x-go-allof-embed-refs: true
      allOf:
      - $ref: '#/components/schemas/WorkItem'
      - type: object
        properties:
          project:
            $ref: '#/components/schemas/ProjectSummary'
          organisation:
            $ref: '#/components/schemas/OrganisationSummary'
type WorkItemView struct {
    // all fields duplicated from root component WorkItem
    // ...
    // ...
    Organisation *OrganisationSummary `json:"organisation,omitempty"`
    Project      *ProjectSummary      `json:"project,omitempty"`
}

to:

type WorkItemView struct {
    // Embedded struct due to allOf(#/components/schemas/WorkItem)
    WorkItem `yaml:",inline"`
    // Embedded fields due to inline allOf schema
    Organisation *OrganisationSummary `json:"organisation,omitempty"`
    Project      *ProjectSummary      `json:"project,omitempty"`
}

This helps build reusable functions for "extendable" types - e.g. I have a function to populate WorkItem - now if I extend work item to add other fields for other API paths (like above example), I can reuse the same function to manage the WorkItem nested struct, rather than rebuilding an entire new function for the extended type.

clarkjohnd avatar Sep 12 '25 14:09 clarkjohnd

Kusari Inspector

Kusari Analysis Results:

Proceed with these changes
✅ No Flagged Issues Detected All values appear to be within acceptable risk parameters.

No pinned version dependency changes, code issues or exposed secrets detected!

[!NOTE] View full detailed analysis result for more information on the output and the checks that were run.


@kusari-inspector rerun - Trigger a re-analysis of this PR @kusari-inspector feedback [your message] - Send feedback to our AI and team See Kusari's documentation for setup and configuration. Commit: 53890386d20a047d4f44e6615d03d7279776e8c9, performed at: 2025-09-12T14:29:19Z

Found this helpful? Give it a 👍 or 👎 reaction!

kusari-inspector[bot] avatar Sep 12 '25 14:09 kusari-inspector[bot]

Would love to see this merged, good job!

marcoabreu avatar Dec 10 '25 14:12 marcoabreu