astahmer / openapi-zod-client

Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)
openapi-zod-client.vercel.app
788 stars 84 forks source link

Add support for null value in enums when using `--export-types` #227

Closed mayorandrew closed 1 year ago

mayorandrew commented 1 year ago

OpenAPI 3.0.3 Data Types are defined by JSON Schema Specification Wright Draft 00.

However, the specification mentions that "null is not supported as a type" and the nullable keyword should be used instead. While it is a valid solution in most cases, it is not possible to use nullable together with $ref. One possible workaround is to define a Null schema and use it in combination with oneOf, like so:

{
  "oneOf": [
    { "$ref": "#/components/schemas/MySchema" },
    {
      "type": "string",
      "enum": [null],
      "nullable": true
    }
  ]
}

It may look contradictory, but according to the enum section of JSON Schema Validation Wright Draft 00:

The value of this keyword MUST be an array. This array SHOULD have at least one element. Elements in the array SHOULD be unique.

Elements in the array MAY be of any type, including null.

An instance validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value.

This means that null is a possible value for the "enum" validation of "type" "string".

This schema also passes the swagger-cli validate check.

The openapi-zod-client library currently crashes when generating a TypeScript type for this construct. Additionally, the generated zod schemas are not correct when using a null value in "enum" along with other values. This PR fixes that.

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
openapi-zod-client ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 22, 2023 6:00pm
astahmer commented 1 year ago

thanks for working on this !