GREsau / schemars

Generate JSON Schema documents from Rust code
https://graham.cool/schemars/
MIT License
793 stars 221 forks source link

Derive macro and validation attrs for newtypes #121

Closed rudolphfroger-ds closed 1 week ago

rudolphfroger-ds commented 2 years ago

It looks like schemars validation attrs get lost when applied to newtypes in combination with using derive for JsonSchema. I think because the derive for JsonSchema assumes that it's not a field but a container and containers do not have validation attrs. The metadata attrs work fine on newtypes. Hopefully this description is clear enough, I can write a small sample to show you when the validation attrs are lost if that makes it easier to understand.

Manually implementing the JsonSchema trait does work for newtypes.

GREsau commented 1 month ago

Is this still a problem? I just tried this:

#[derive(JsonSchema)]
pub struct MyStruct(#[schemars(range(min = 1, max = 10))] pub i32);

fn main() {
    let schema = schema_for!(MyStruct);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}

And the generated schema has both minimum and maximum set:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "MyStruct",
  "type": "integer",
  "format": "int32",
  "maximum": 10,
  "minimum": 1
}
rudolphfroger commented 4 weeks ago

Sorry, but I do not use schemars at the moment. I see lot's of changes since this report from 2021, so it could very well be solved. Thanks for your reply and the great work on schemars.

GREsau commented 1 week ago

I believe this is working correctly when #[schemars(range(...))] is set on a field, including the single field of a newtype struct.

Previous versions of schemars would silently ignore that attribute when placed on the struct itself, but that now fails to compile since alpha.12