Refactor nullable schema generation

This commit is contained in:
Graham Esau 2019-08-06 07:48:44 +01:00
parent 650c434c1a
commit 48465b51cf
2 changed files with 16 additions and 23 deletions

View file

@ -7,7 +7,7 @@ use std::iter::FromIterator;
#[derive(Debug, PartialEq, Clone)]
pub struct SchemaSettings {
pub option_nullable: bool,
pub option_any_of_null: bool,
pub option_add_null_type: bool,
pub bool_schemas: BoolSchemas,
pub definitions_path: String,
}
@ -23,7 +23,7 @@ impl Default for SchemaSettings {
fn default() -> SchemaSettings {
SchemaSettings {
option_nullable: false,
option_any_of_null: true,
option_add_null_type: true,
bool_schemas: BoolSchemas::Enable,
definitions_path: "#/definitions/".to_owned(),
}
@ -39,7 +39,7 @@ impl SchemaSettings {
pub fn openapi3() -> SchemaSettings {
SchemaSettings {
option_nullable: true,
option_any_of_null: false,
option_add_null_type: false,
bool_schemas: BoolSchemas::AdditionalPropertiesOnly,
definitions_path: "#/components/schemas/".to_owned(),
}

View file

@ -266,30 +266,23 @@ impl<T: MakeSchema> MakeSchema for Option<T> {
}
fn make_schema(gen: &mut SchemaGenerator) -> Schema {
let settings = gen.settings();
let make_any_of = settings.option_any_of_null;
let set_nullable = settings.option_nullable;
let schema = match gen.subschema_for::<T>() {
Schema::Bool(true) => true.into(),
Schema::Bool(false) => <()>::make_schema(gen),
schema => {
if make_any_of {
SchemaObject {
any_of: Some(vec![schema, <()>::make_schema(gen)]),
..Default::default()
}
.into()
} else {
schema
let mut schema = gen.subschema_for::<T>();
if gen.settings().option_add_null_type {
schema = match schema {
Schema::Bool(true) => Schema::Bool(true),
Schema::Bool(false) => <()>::make_schema(gen),
schema => SchemaObject {
any_of: Some(vec![schema, <()>::make_schema(gen)]),
..Default::default()
}
.into(),
}
};
if set_nullable {
let deref = gen.try_get_schema_object(&schema);
}
if gen.settings().option_nullable {
let mut deref = gen.try_get_schema_object(&schema);
debug_assert!(deref.is_some(), "Could not get schema object: {:?}", schema);
if let Some(mut schema) = deref {
if let Some(ref mut schema) = deref {
schema.extensions.insert("nullable".to_owned(), json!(true));
return Schema::Object(schema);
}
};
schema