Skip to content

Commit

Permalink
Add Discriminator mapping (#752)
Browse files Browse the repository at this point in the history
Add discriminator mapping field with test case.
  • Loading branch information
1lutz authored Sep 22, 2023
1 parent d7280eb commit 6dc73eb
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions utoipa/src/openapi/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,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<String, String>,
}

impl Discriminator {
Expand All @@ -299,6 +305,7 @@ impl Discriminator {
pub fn new<I: Into<String>>(property_name: I) -> Self {
Self {
property_name: property_name.into(),
mapping: BTreeMap::new(),
}
}
}
Expand Down Expand Up @@ -2037,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::<BTreeMap<_, _>>();
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"
}
}
})
);
}
}

0 comments on commit 6dc73eb

Please sign in to comment.