|
| 1 | +//! Schema specification for [OpenAPI 3.1](https://github.com/OAI/OpenAPI-Specification/blob/HEAD/versions/3.1.0.md) |
| 2 | +
|
| 3 | +use std::collections::BTreeMap; |
| 4 | + |
| 5 | +use serde::{Deserialize, Serialize}; |
| 6 | + |
| 7 | +/// A discriminator object can be used to aid in serialization, deserialization, and validation when |
| 8 | +/// payloads may be one of a number of different schemas. |
| 9 | +/// |
| 10 | +/// The discriminator is a specific object in a schema which is used to inform the consumer of the |
| 11 | +/// document of an alternative schema based on the value associated with it. |
| 12 | +/// |
| 13 | +/// See <https://github.com/OAI/OpenAPI-Specification/blob/HEAD/versions/3.1.0.md#discriminator-object>. |
| 14 | +#[derive(Debug, Clone, PartialEq, Default, Deserialize, Serialize)] |
| 15 | +#[serde(rename_all = "camelCase")] |
| 16 | +pub struct Discriminator { |
| 17 | + /// Name of the property in the payload that will hold the discriminator value. |
| 18 | + pub property_name: String, |
| 19 | + |
| 20 | + /// Object to hold mappings between payload values and schema names or references. |
| 21 | + /// |
| 22 | + /// When using the discriminator, inline schemas will not be considered. |
| 23 | + #[serde(skip_serializing_if = "Option::is_none")] |
| 24 | + pub mapping: Option<BTreeMap<String, String>>, |
| 25 | +} |
| 26 | + |
| 27 | +#[cfg(test)] |
| 28 | +mod tests { |
| 29 | + use super::*; |
| 30 | + |
| 31 | + #[test] |
| 32 | + fn discriminator_property_name_parsed_correctly() { |
| 33 | + let spec = "propertyName: testName"; |
| 34 | + let discriminator = serde_yml::from_str::<Discriminator>(spec).unwrap(); |
| 35 | + assert_eq!("testName", discriminator.property_name); |
| 36 | + assert!(discriminator.mapping.is_none()); |
| 37 | + } |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn discriminator_mapping_parsed_correctly() { |
| 41 | + let spec = indoc::indoc! {" |
| 42 | + propertyName: petType |
| 43 | + mapping: |
| 44 | + dog: '#/components/schemas/Dog' |
| 45 | + cat: '#/components/schemas/Cat' |
| 46 | + monster: 'https://gigantic-server.com/schemas/Monster/schema.json' |
| 47 | + "}; |
| 48 | + let discriminator = serde_yml::from_str::<Discriminator>(spec).unwrap(); |
| 49 | + |
| 50 | + assert_eq!("petType", discriminator.property_name); |
| 51 | + let mapping = discriminator.mapping.unwrap(); |
| 52 | + |
| 53 | + assert_eq!("#/components/schemas/Dog", mapping.get("dog").unwrap()); |
| 54 | + assert_eq!("#/components/schemas/Cat", mapping.get("cat").unwrap()); |
| 55 | + assert_eq!( |
| 56 | + "https://gigantic-server.com/schemas/Monster/schema.json", |
| 57 | + mapping.get("monster").unwrap() |
| 58 | + ); |
| 59 | + } |
| 60 | +} |
0 commit comments