salvo_oapi/openapi/schema/
any_of.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::SchemaType;
5use crate::{Discriminator, PropMap, RefOr, Schema};
6
7/// AnyOf [Composite Object][allof] component holds
8/// multiple components together where API endpoint will return a combination of all of them.
9///
10/// See [`Schema::AnyOf`] for more details.
11///
12/// [allof]: https://spec.openapis.org/oas/latest.html#components-object
13#[non_exhaustive]
14#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
15pub struct AnyOf {
16    /// Components of _AnyOf_ component.
17    #[serde(rename = "anyOf")]
18    pub items: Vec<RefOr<Schema>>,
19
20    /// Type of [`AnyOf`] e.g. `SchemaType::basic(BasicType::Object)` for `object`.
21    ///
22    /// By default this is [`SchemaType::AnyValue`] as the type is defined by items
23    /// themselves.
24    #[serde(
25        rename = "type",
26        default = "SchemaType::any",
27        skip_serializing_if = "SchemaType::is_any_value"
28    )]
29    pub schema_type: SchemaType,
30
31    /// Changes the [`AnyOf`] title.
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub title: Option<String>,
34
35    /// Description of the [`AnyOf`]. Markdown syntax is supported.
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub description: Option<String>,
38
39    /// Default value which is provided when user has not provided the input in Swagger UI.
40    #[serde(rename = "default", skip_serializing_if = "Option::is_none")]
41    pub default_value: Option<Value>,
42
43    /// Examples shown in UI of the value for richer documentation.
44    #[serde(skip_serializing_if = "Vec::is_empty", default)]
45    pub examples: Vec<Value>,
46
47    /// Optional discriminator field can be used to aid deserialization, serialization and validation of a
48    /// specific schema.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub discriminator: Option<Discriminator>,
51
52    /// Optional extensions `x-something`.
53    #[serde(skip_serializing_if = "PropMap::is_empty", flatten)]
54    pub extensions: PropMap<String, serde_json::Value>,
55}
56
57impl Default for AnyOf {
58    fn default() -> Self {
59        Self {
60            items: Default::default(),
61            schema_type: SchemaType::AnyValue,
62            title: None,
63            description: Default::default(),
64            default_value: Default::default(),
65            examples: Default::default(),
66            discriminator: Default::default(),
67            extensions: Default::default(),
68        }
69    }
70}
71
72impl AnyOf {
73    /// Construct a new empty [`AnyOf`]. This is effectively same as calling [`AnyOf::default`].
74    pub fn new() -> Self {
75        Default::default()
76    }
77
78    /// Construct a new [`AnyOf`] component with given capacity.
79    ///
80    /// AnyOf component is then able to contain number of components without
81    /// reallocating.
82    ///
83    /// # Examples
84    ///
85    /// Create [`AnyOf`] component with initial capacity of 5.
86    /// ```
87    /// # use salvo_oapi::schema::AnyOf;
88    /// let one_of = AnyOf::with_capacity(5);
89    /// ```
90    pub fn with_capacity(capacity: usize) -> Self {
91        Self {
92            items: Vec::with_capacity(capacity),
93            ..Default::default()
94        }
95    }
96    /// Adds a given [`Schema`] to [`AnyOf`] [Composite Object][composite]
97    ///
98    /// [composite]: https://spec.openapis.org/oas/latest.html#components-object
99    pub fn item<I: Into<RefOr<Schema>>>(mut self, component: I) -> Self {
100        self.items.push(component.into());
101        self
102    }
103
104    /// Add or change type of the object e.g. to change type to _`string`_
105    /// use value `SchemaType::Type(Type::String)`.
106    pub fn schema_type<T: Into<SchemaType>>(mut self, schema_type: T) -> Self {
107        self.schema_type = schema_type.into();
108        self
109    }
110
111    /// Add or change the title of the [`AnyOf`].
112    pub fn title(mut self, title: impl Into<String>) -> Self {
113        self.title = Some(title.into());
114        self
115    }
116
117    /// Add or change optional description for `AnyOf` component.
118    pub fn description(mut self, description: impl Into<String>) -> Self {
119        self.description = Some(description.into());
120        self
121    }
122
123    /// Add or change default value for the object which is provided when user has not provided the input in Swagger UI.
124    pub fn default_value(mut self, default: Value) -> Self {
125        self.default_value = Some(default);
126        self
127    }
128
129    /// Add or change example shown in UI of the value for richer documentation.
130    pub fn add_example<V: Into<Value>>(mut self, example: V) -> Self {
131        self.examples.push(example.into());
132        self
133    }
134
135    /// Add or change discriminator field of the composite [`AnyOf`] type.
136    pub fn discriminator(mut self, discriminator: Discriminator) -> Self {
137        self.discriminator = Some(discriminator);
138        self
139    }
140
141    /// Add openapi extension (`x-something`) for [`AnyOf`].
142    pub fn add_extension<K: Into<String>>(mut self, key: K, value: serde_json::Value) -> Self {
143        self.extensions.insert(key.into(), value);
144        self
145    }
146}
147
148impl From<AnyOf> for Schema {
149    fn from(one_of: AnyOf) -> Self {
150        Self::AnyOf(one_of)
151    }
152}
153
154impl From<AnyOf> for RefOr<Schema> {
155    fn from(one_of: AnyOf) -> Self {
156        Self::Type(Schema::AnyOf(one_of))
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use assert_json_diff::assert_json_eq;
163    use serde_json::json;
164
165    use super::*;
166
167    #[test]
168    fn test_build_any_of() {
169        let any_of = AnyOf::with_capacity(5)
170            .title("title")
171            .description("description")
172            .default_value(Value::String("default".to_string()))
173            .add_example(Value::String("example1".to_string()))
174            .add_example(Value::String("example2".to_string()))
175            .discriminator(Discriminator::new("discriminator".to_string()));
176
177        assert_eq!(any_of.items.len(), 0);
178        assert_eq!(any_of.items.capacity(), 5);
179        assert_json_eq!(
180            any_of,
181            json!({
182                "anyOf": [],
183                "title": "title",
184                "description": "description",
185                "default": "default",
186                "examples": ["example1", "example2"],
187                "discriminator": {
188                    "propertyName": "discriminator"
189                }
190            })
191        )
192    }
193
194    #[test]
195    fn test_schema_from_any_of() {
196        let any_of = AnyOf::new();
197        let schema = Schema::from(any_of);
198        assert_json_eq!(
199            schema,
200            json!({
201                "anyOf": []
202            })
203        )
204    }
205
206    #[test]
207    fn test_refor_schema_from_any_of() {
208        let any_of = AnyOf::new();
209        let ref_or: RefOr<Schema> = RefOr::from(any_of);
210        assert_json_eq!(
211            ref_or,
212            json!({
213                "anyOf": []
214            })
215        )
216    }
217
218    #[test]
219    fn test_anyof_with_extensions() {
220        let expected = json!("value");
221        let json_value = AnyOf::new().add_extension("x-some-extension", expected.clone());
222
223        let value = serde_json::to_value(&json_value).unwrap();
224        assert_eq!(value.get("x-some-extension"), Some(&expected));
225    }
226}