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

bug: strict server interface doesn't marshal additionalProperties in complex object

Open reinkrul opened this issue 1 year ago • 0 comments

When generating a Strict Server interface with a type that has fields, as well as additionalProperties, the additionalProperties don't get marshalled.

Failing test https://github.com/deepmap/oapi-codegen/pull/1579

Cause For a type with fields and additionalProperties, a custom MarshalJSON() function is generated to handle additionalProperties marshalling. However, for a strict server interface a response type is generated that aliases/subtypes the referenced response type (e.g. type CreateUserResponse becomes CreateUserJSON200Response CreateUserResponse). But, this strict server interface-specific type does not implement json.Marshaler (to delegate it to the aliased/subtype), thus the custom MarshalJSON() function is never called.

Versions

github.com/oapi-codegen/[email protected]
github.com/deepmap/oapi-codegen/v2/cmd/[email protected]

Example

openapi: "3.0.1"
components:
  schemas:
    ComplexObject:
      type: object
      properties:
        field1:
         type: string
      additionalProperties: {}
paths:
  /test:
    get:
      operationId: test
      responses:
        200:
          description: test
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ComplexObject"

Workaround There's an ugly workaround, you can create a MarshalJSON() function for the strict server interface type and delegate it to the underlying type, e.g.:

var _ json.Marshaler = Test200JSONResponse{}

func (response Test200JSONResponse) MarshalJSON() ([]byte, error) {
	return json.Marshal(ComplexObject(response))
}

reinkrul avatar Apr 26 '24 15:04 reinkrul