elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
9.1k stars 193 forks source link

Nullable field for types as documented in OpenAPI 3.0 #669

Open Singha360 opened 1 month ago

Singha360 commented 1 month ago

What is the problem this feature would solve?

OpenAPI has an optional nullable boolean field for data types which currently the TypeBox interface exposed by Elysia does not implement.

Note that there is no null type; instead, the nullable attribute is used as a modifier of the base type.

# Correct
type: integer
nullable: true

# Incorrect
type: null

# Incorrect as well
type:
  - integer
  - null

Currently this code:

my_field: t.Nullable(
    t.Number({
        examples: 120
    })
)

Produces this:

"my_field": {
    "anyOf": [{
            "type": "null"
        },
        {
            "examples": 120,
            "type": "number"
        }
    ]
}

What is the feature you are proposing to solve the problem?

duration_seconds:
    t.Number({
        examples: 120,
        nullable: true // Add this field
    })

Or use the currently available t.Nullable validator to have it generate the appropriate OpenAPI schema for nullable type.

Personally I am not too opinionated about the implementation, however I do think having both as an option would be best.

What alternatives have you considered?

None, couldn't make it work.

xdream77 commented 2 weeks ago

Actually you can do that with the Unsafe method of Typebox.

There is an example in there for exactly your usecase.