geut / openapi-box

Generate TypeBox schemas from your openapi.
MIT License
21 stars 4 forks source link

nullable ignored in OpenAPI 3.0.3 spec #9

Closed iivo-k closed 4 weeks ago

iivo-k commented 1 month ago

I'm having an issue with @geut/openapi-box v5.0.5 (and @sinclair/typebox v0.33.7). Nullable values with OpenAPI schema version 3.0.3 seem to be ignored in the generated types.

openapi: 3.0.3
info:
  description: Title
  version: 1.0.0
servers:
  - url: "https"

components:
  schemas:
    Test:
      type: object
      properties:
        testVal:
          type: string
          description: Should be a 2 character string, null or undefined
          minLength: 2
          maxLength: 2
          nullable: true

results in

Test: T.Object({
  testVal: T.Optional(T.String({ minLength: 2, maxLength: 2 })),
})

which does not allow null.

However when using OpenAPI 3.1.0 with

openapi: 3.1.0
info:
  description: Title
  version: 1.0.0
servers:
  - url: "https"

components:
  schemas:
    TestObject:
      type: object
      properties:
        testValue:
          oneOf:
            - type: string
              description: Should be a 2 character string, null or undefined
              minLength: 2
              maxLength: 2
            - type: "null"

the result is

TestObject: T.Object({
  testValue: T.Optional(
    T.Union([T.String({ minLength: 2, maxLength: 2 }), T.Null()]),
  ),
 })

which works as expected, allowing null values.

Would it be possible to handle nullable in OpenAPI 3.0.3 like this, generating a null union for nullable fields?

iivo-k commented 1 month ago

I tinkered with this myself and got it to work at least for my case by adding unions with Type.Null() as mentioned in https://github.com/sinclairzx81/typebox/pull/118. Made a pull request too, in case it's helpful: https://github.com/geut/openapi-box/pull/10 Test case isn't exhaustive and I'm not sure if there should be some checks so as not to do this with OpenAPI 3.1.0.

tinchoz49 commented 4 weeks ago

fixed in 5.0.6