From d5a379287247215ab432b3d351d08d52a8345bf5 Mon Sep 17 00:00:00 2001 From: 1lutz Date: Sat, 19 Aug 2023 08:54:54 +0000 Subject: [PATCH 1/2] add discriminator mapping --- utoipa/src/openapi/schema.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/utoipa/src/openapi/schema.rs b/utoipa/src/openapi/schema.rs index 1759ccd3..fd622382 100644 --- a/utoipa/src/openapi/schema.rs +++ b/utoipa/src/openapi/schema.rs @@ -284,6 +284,10 @@ pub struct Discriminator { /// Defines a discriminator property name which must be found within all composite /// objects. pub property_name: String, + + // An object to hold mappings between payload values and schema names or references. + #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] + pub mapping: BTreeMap, } impl Discriminator { @@ -299,6 +303,7 @@ impl Discriminator { pub fn new>(property_name: I) -> Self { Self { property_name: property_name.into(), + mapping: BTreeMap::new(), } } } From c2834c575716219ba4226fc3ac6ed0c1ae0bd01e Mon Sep 17 00:00:00 2001 From: 1lutz Date: Wed, 20 Sep 2023 09:32:13 +0000 Subject: [PATCH 2/2] improve comment and add test for mapping --- utoipa/src/openapi/schema.rs | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/utoipa/src/openapi/schema.rs b/utoipa/src/openapi/schema.rs index 50150d9f..53d3c76a 100644 --- a/utoipa/src/openapi/schema.rs +++ b/utoipa/src/openapi/schema.rs @@ -285,7 +285,9 @@ pub struct Discriminator { /// objects. pub property_name: String, - // An object to hold mappings between payload values and schema names or references. + /// An object to hold mappings between payload values and schema names or references. + /// This field can only be populated manually. There is no macro support and no + /// validation. #[serde(skip_serializing_if = "BTreeMap::is_empty", default)] pub mapping: BTreeMap, } @@ -2042,4 +2044,34 @@ mod tests { assert_eq!(json_str, json_de_str); } + + #[test] + fn serialize_discriminator_with_mapping() { + let mut discriminator = Discriminator::new("type"); + discriminator.mapping = [("int".to_string(), "#/components/schemas/MyInt".to_string())] + .into_iter() + .collect::>(); + let one_of = OneOfBuilder::new() + .item(Ref::from_schema_name("MyInt")) + .discriminator(Some(discriminator)) + .build(); + let json_value = serde_json::to_value(one_of).unwrap(); + + assert_json_eq!( + json_value, + json!({ + "oneOf": [ + { + "$ref": "#/components/schemas/MyInt" + } + ], + "discriminator": { + "propertyName": "type", + "mapping": { + "int": "#/components/schemas/MyInt" + } + } + }) + ); + } }