From 1f79496e7e21ddf96334c631624f7d938c0a8c6b Mon Sep 17 00:00:00 2001 From: Chrislearn Young Date: Mon, 27 Nov 2023 08:10:20 +0800 Subject: [PATCH] Add Discriminator mapping to oapi (#512) --- crates/oapi/src/openapi/schema/mod.rs | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/oapi/src/openapi/schema/mod.rs b/crates/oapi/src/openapi/schema/mod.rs index ed607a7c5..8accf2470 100644 --- a/crates/oapi/src/openapi/schema/mod.rs +++ b/crates/oapi/src/openapi/schema/mod.rs @@ -85,6 +85,12 @@ 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. + /// 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, } impl Discriminator { @@ -100,6 +106,7 @@ impl Discriminator { pub fn new>(property_name: I) -> Self { Self { property_name: property_name.into(), + mapping: BTreeMap::new(), } } } @@ -770,4 +777,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" + } + } + }) + ); + } }