Fix schema generation for flatten Options

This commit is contained in:
Graham Esau 2019-10-19 21:03:34 +01:00
parent 5bf8b30753
commit 18c2d417e3
5 changed files with 34 additions and 13 deletions

View file

@ -46,8 +46,16 @@ impl<T: JsonSchema> JsonSchema for Option<T> {
schema schema
} }
fn json_schema_non_null(gen: &mut SchemaGenerator) -> Schema { fn json_schema_optional(gen: &mut SchemaGenerator) -> Schema {
T::json_schema_non_null(gen) let mut schema = T::json_schema_optional(gen);
if let Schema::Object(SchemaObject {
object: Some(ref mut object_validation),
..
}) = schema
{
object_validation.required.clear();
}
schema
} }
} }

View file

@ -19,6 +19,10 @@ macro_rules! deref_impl {
fn json_schema(gen: &mut SchemaGenerator) -> Schema { fn json_schema(gen: &mut SchemaGenerator) -> Schema {
T::json_schema(gen) T::json_schema(gen)
} }
fn json_schema_optional(gen: &mut SchemaGenerator) -> Schema {
T::json_schema_optional(gen)
}
} }
}; };
} }

View file

@ -27,7 +27,7 @@ pub trait JsonSchema {
fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema; fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema;
#[doc(hidden)] #[doc(hidden)]
fn json_schema_non_null(gen: &mut gen::SchemaGenerator) -> Schema { fn json_schema_optional(gen: &mut gen::SchemaGenerator) -> Schema {
Self::json_schema(gen) Self::json_schema(gen)
} }
} }

View file

@ -4,31 +4,40 @@ use schemars::{schema_for, JsonSchema};
#[derive(Debug, JsonSchema)] #[derive(Debug, JsonSchema)]
struct Flat { struct Flat {
foo: f32, f: f32,
bar: bool, b: bool,
baz: String, s: String,
foobar: Vec<i32>, #[serde(default)]
os: String,
v: Vec<i32>,
} }
#[derive(Debug, JsonSchema)] #[derive(Debug, JsonSchema)]
#[schemars(rename = "Flat")] #[schemars(rename = "Flat")]
struct Deep1 { struct Deep1 {
foo: f32, f: f32,
#[serde(flatten)] #[schemars(flatten)]
deep2: Deep2, deep2: Deep2,
foobar: Vec<i32>, v: Vec<i32>,
} }
#[derive(Debug, JsonSchema)] #[derive(Debug, JsonSchema)]
struct Deep2 { struct Deep2 {
bar: bool, b: bool,
#[serde(flatten)] #[serde(flatten)]
deep3: Deep3, deep3: Deep3,
#[serde(flatten)]
deep4: Box<Option<Option<Box<Deep4>>>>,
} }
#[derive(Debug, JsonSchema)] #[derive(Debug, JsonSchema)]
struct Deep3 { struct Deep3 {
baz: &'static str, s: &'static str,
}
#[derive(Debug, JsonSchema)]
struct Deep4 {
os: &'static str,
} }
#[test] #[test]

View file

@ -318,7 +318,7 @@ fn schema_for_struct(fields: &[Field], cattrs: &attr::Container) -> TokenStream
let flattens = flat.iter().map(|field| { let flattens = flat.iter().map(|field| {
let ty = get_json_schema_type(field); let ty = get_json_schema_type(field);
quote_spanned! {field.original.span()=> quote_spanned! {field.original.span()=>
.flatten(<#ty>::json_schema_non_null(gen)) .flatten(<#ty>::json_schema_optional(gen))
} }
}); });