Fix schema generation for flatten Options
This commit is contained in:
parent
5bf8b30753
commit
18c2d417e3
5 changed files with 34 additions and 13 deletions
|
@ -46,8 +46,16 @@ impl<T: JsonSchema> JsonSchema for Option<T> {
|
|||
schema
|
||||
}
|
||||
|
||||
fn json_schema_non_null(gen: &mut SchemaGenerator) -> Schema {
|
||||
T::json_schema_non_null(gen)
|
||||
fn json_schema_optional(gen: &mut SchemaGenerator) -> Schema {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -19,6 +19,10 @@ macro_rules! deref_impl {
|
|||
fn json_schema(gen: &mut SchemaGenerator) -> Schema {
|
||||
T::json_schema(gen)
|
||||
}
|
||||
|
||||
fn json_schema_optional(gen: &mut SchemaGenerator) -> Schema {
|
||||
T::json_schema_optional(gen)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
@ -27,7 +27,7 @@ pub trait JsonSchema {
|
|||
fn json_schema(gen: &mut gen::SchemaGenerator) -> Schema;
|
||||
|
||||
#[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)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,31 +4,40 @@ use schemars::{schema_for, JsonSchema};
|
|||
|
||||
#[derive(Debug, JsonSchema)]
|
||||
struct Flat {
|
||||
foo: f32,
|
||||
bar: bool,
|
||||
baz: String,
|
||||
foobar: Vec<i32>,
|
||||
f: f32,
|
||||
b: bool,
|
||||
s: String,
|
||||
#[serde(default)]
|
||||
os: String,
|
||||
v: Vec<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, JsonSchema)]
|
||||
#[schemars(rename = "Flat")]
|
||||
struct Deep1 {
|
||||
foo: f32,
|
||||
#[serde(flatten)]
|
||||
f: f32,
|
||||
#[schemars(flatten)]
|
||||
deep2: Deep2,
|
||||
foobar: Vec<i32>,
|
||||
v: Vec<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, JsonSchema)]
|
||||
struct Deep2 {
|
||||
bar: bool,
|
||||
b: bool,
|
||||
#[serde(flatten)]
|
||||
deep3: Deep3,
|
||||
#[serde(flatten)]
|
||||
deep4: Box<Option<Option<Box<Deep4>>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, JsonSchema)]
|
||||
struct Deep3 {
|
||||
baz: &'static str,
|
||||
s: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Debug, JsonSchema)]
|
||||
struct Deep4 {
|
||||
os: &'static str,
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -318,7 +318,7 @@ fn schema_for_struct(fields: &[Field], cattrs: &attr::Container) -> TokenStream
|
|||
let flattens = flat.iter().map(|field| {
|
||||
let ty = get_json_schema_type(field);
|
||||
quote_spanned! {field.original.span()=>
|
||||
.flatten(<#ty>::json_schema_non_null(gen))
|
||||
.flatten(<#ty>::json_schema_optional(gen))
|
||||
}
|
||||
});
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue