Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Poem openapi Option<T> ToJSON & Type implementation mismatch #913

Open
Nahuel-M opened this issue Nov 19, 2024 · 0 comments
Open

Poem openapi Option<T> ToJSON & Type implementation mismatch #913

Nahuel-M opened this issue Nov 19, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@Nahuel-M
Copy link
Contributor

Nahuel-M commented Nov 19, 2024

The ToJSON for an Option<T> is implemented as follows:

impl<T: ToJSON> ToJSON for Option<T> {
    fn to_json(&self) -> Option<Value> {
        match self {
            Some(value) => value.to_json(),
            None => Some(Value::Null),
        }
    }
}

This means { variable: null } is returned if it is a None in Rust.
However, the implementation of the Type trait for Option<T> simply passes all implementations to T, except for IS_REQUIRED, which is set to false. For example:

struct Test{
    field1: Option<String>,
}

leads to the following openapi spec:

"Test": {
        "type": "object",
        "required": [
        ],
        "properties": {
          "field1": {
            "type": "string"
          },
        }
      },

I believe this is a mismatch. The generated openapi spec suggests the field field1 either IS there and is a string, or isn't there at all, but the ToJSON impl will ensure the field is always there, but is possibly null.

As far as I can see there's two options (heh) here:

  • Use the nullable annotation for options in the openapi spec
  • Don't return Value::Null in the ToJSON impl of Option<T>, but return None

I'm interested in your thoughts!

@Nahuel-M Nahuel-M added the bug Something isn't working label Nov 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant