asteasolutions / zod-to-openapi

A library that generates OpenAPI (Swagger) docs from Zod schemas
MIT License
955 stars 60 forks source link

.nullish() should display <itemType> | null | undefined in swagger #232

Closed kevbarns closed 5 months ago

kevbarns commented 5 months ago

exemple :

    job_description: z.string().nullish(),
    job_employer_description: z.string().nullish(),

should display in swagger :

custom_address: string | null | undefined
custom_geo_coordinates: string | null | undefined

As of today, undefined option is not displayed

Zod nullish doc : https://zod.dev/?id=nullish

AGalabov commented 5 months ago

@kevbarns I am not sure I understand what you mean by "in Swagger".

The following minimal piece of code:

extendZodWithOpenApi(z);

const generator = new OpenApiGeneratorV3([
  z.object({ test: z.string().nullish() }).openapi('Schema'),
]);
const doc = generator.generateComponents();

console.log(JSON.stringify(doc, null, 4));

Produces the following result:

{
    "components": {
        "schemas": {
            "Schema": {
                "type": "object",
                "properties": {
                    "test": {
                        "type": "string",
                        "nullable": true
                    }
                }
            }
        },
        "parameters": {}
    }
}

As you can see the result is a non-required (which is the definition of undefined) nullable field. There is no such thing as undefined in the Open API specification?

So because of that when you just generate a simple string:

extendZodWithOpenApi(z);

const generator = new OpenApiGeneratorV3([
  z.string().nullish().openapi('Schema'),
]);
const doc = generator.generateComponents();

console.log(JSON.stringify(doc, null, 4));

you'd get:

{
    "components": {
        "schemas": {
            "Schema": {
                "type": "string",
                "nullable": true
            }
        },
        "parameters": {}
    }
}

Again there is no way to say that this is an undefined type as this is not valid within Open API