StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
886 stars 71 forks source link

OpenAPI fix for a nullable ref using allOf #103

Closed Bram-dc closed 8 months ago

Bram-dc commented 8 months ago

Context: OpenAPI null or reference issue

I am trying to get correct typings when using a reference and nullable together.

Currently I am using this piece of code to apply a fix to the generated json/openapi schema:

export const fixNullableRefs = (obj: unknown): unknown => {

    if (obj && typeof obj === 'object') {

        if ('$ref' in obj && typeof obj.$ref === 'string') {
            if (Object.keys(obj).length === 1)
                return obj

            return {
                ...obj,
                $ref: undefined,
                allOf: [
                    { $ref: obj.$ref },
                ],
            }
        }

        if (Array.isArray(obj))
            return obj.map(fixNullableRefs)

        return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fixNullableRefs(value)]))

    }

    return obj

}

Would I be doing something wrong or is this an issue in the current script?

Bram-dc commented 8 months ago

It transforms this:

    "picture": {
        "$ref": "#/components/schemas/Picture",
        "nullable": true
    },

into this:

    "picture": {
        "nullable": true,
        "allOf": [
            {
                "$ref": "#/components/schemas/Picture"
            }
        ]
    },
StefanTerdell commented 8 months ago

Fixed in 3.22.4