salvo_oapi/openapi/schema/
all_of.rs

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