lukeautry / tsoa

Build OpenAPI-compliant REST APIs using TypeScript and Node
MIT License
3.57k stars 503 forks source link

Null value for boolean attribute is converted to false. How to alter this behavior? #1444

Closed RohitRox closed 7 months ago

RohitRox commented 1 year ago

This is related to validation. Null values sent for attributes defined as boolean are converted to false.

Sorting

Current & Expected Behavior

When an attribute is defined as a boolean For eg:

interface UserCreateRequest {
    preferredDelivery: boolean
}

and in payload/request body, if null is sent For eg:

{
    "preferredDelivery": null
}

After the request passes through validation, the preferredDelivery's value is observed to be false. The expected behavior is that the null value should have been preserved.

Possible Solution

I understand in some cases this is okay and desired, but is some cases this behavior is needed. And I couldn't find a way to alter this behavior. The validator library (https://github.com/validatorjs/validator.js) seem to have { loose: false } option but I could not find a way to use it here. Any help or guidance on this?

github-actions[bot] commented 1 year ago

Hello there RohitRox 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

WoH commented 1 year ago

Hi there, you can customize the template as well as the route generator (template is simpler and should be sufficient).

However, we should also discuss these groups of coercions and if we want to customize them (i.e. via config or hooks).

However, as is, this is intended behavior, therefore I'll tag this properly.

jchadwick commented 8 months ago

This issue is more obvious (and more obviously a bug vs intended behavior) when the boolean property explicitly allows nulls. e.g.

interface UserCreateRequest {
    preferredDelivery: boolean | null
}

This also improperly converts explicitly null values to false

WoH commented 8 months ago

This issue is more obvious (and more obviously a bug vs intended behavior) when the boolean property explicitly allows nulls. e.g.

interface UserCreateRequest {
    preferredDelivery: boolean | null
}

This also improperly converts explicitly null values to false

Try null | boolean

jchadwick commented 8 months ago

WOW, WAIT... WHAT!?

Yeah, that works. But why?? And can we make the more "standard" boolean | null work as well?

WoH commented 8 months ago

Validation is from left to right. Thus, so is coercion.

So:

vs.

We can make it work, by rewriting the entire metadata layer to output json schemas for ajv or basically reimplement ajv ourselves. I dont have plans to do either.