salvo_oapi/openapi/encoding.rs
1//! Implements encoding object for content.
2
3use serde::{Deserialize, Serialize};
4
5use super::parameter::ParameterStyle;
6use super::{Header, PropMap};
7
8/// A single encoding definition applied to a single schema [`Object
9/// property`](crate::openapi::schema::Object::properties).
10#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq)]
11#[serde(rename_all = "camelCase")]
12#[non_exhaustive]
13pub struct Encoding {
14 /// The Content-Type for encoding a specific property. Default value depends on the property
15 /// type: for string with format being binary – `application/octet-stream`; for other primitive
16 /// types – `text/plain`; for object - `application/json`; for array – the default is defined
17 /// based on the inner type. The value can be a specific media type (e.g. `application/json`),
18 /// a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types.
19 #[serde(skip_serializing_if = "Option::is_none")]
20 pub content_type: Option<String>,
21
22 /// A map allowing additional information to be provided as headers, for example
23 /// Content-Disposition. Content-Type is described separately and SHALL be ignored in this
24 /// section. This property SHALL be ignored if the request body media type is not a multipart.
25 #[serde(default, skip_serializing_if = "PropMap::is_empty")]
26 pub headers: PropMap<String, Header>,
27
28 /// Describes how a specific property value will be serialized depending on its type. See
29 /// Parameter Object for details on the style property. The behavior follows the same values as
30 /// query parameters, including default values. This property SHALL be ignored if the request
31 /// body media type is not `application/x-www-form-urlencoded`.
32 #[serde(skip_serializing_if = "Option::is_none")]
33 pub style: Option<ParameterStyle>,
34
35 /// When this is true, property values of type array or object generate separate parameters for
36 /// each value of the array, or key-value-pair of the map. For other types of properties this
37 /// property has no effect. When style is form, the default value is true. For all other
38 /// styles, the default value is false. This property SHALL be ignored if the request body
39 /// media type is not `application/x-www-form-urlencoded`.
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub explode: Option<bool>,
42
43 /// When this is true, values are serialized using reserved expansion, letting RFC3986's
44 /// reserved character set `:/?#[]@!$&'()*+,;=` pass through unchanged. The default value is
45 /// false.
46 ///
47 /// In OpenAPI 3.1 this only applied to `application/x-www-form-urlencoded` request bodies;
48 /// OpenAPI 3.2 generalizes it to RFC6570-style serialization, and it has no effect for
49 /// `multipart/form-data`.
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub allow_reserved: Option<bool>,
52
53 /// Nested encoding applied by property name, mirroring the [`Content::encoding`] field of the
54 /// enclosing media type. Added in OpenAPI 3.2.
55 ///
56 /// Must not be combined with [`Encoding::prefix_encoding`] or [`Encoding::item_encoding`].
57 ///
58 /// [`Content::encoding`]: crate::openapi::Content::encoding
59 #[serde(skip_serializing_if = "PropMap::is_empty", default)]
60 pub encoding: PropMap<String, Encoding>,
61
62 /// Nested positional encoding, mirroring the [`Content::prefix_encoding`] field of the
63 /// enclosing media type. Added in OpenAPI 3.2.
64 ///
65 /// [`Content::prefix_encoding`]: crate::openapi::Content::prefix_encoding
66 #[serde(skip_serializing_if = "Vec::is_empty", default)]
67 pub prefix_encoding: Vec<Encoding>,
68
69 /// Nested encoding applied to every remaining array item, mirroring the
70 /// [`Content::item_encoding`] field of the enclosing media type. Added in OpenAPI 3.2.
71 ///
72 /// [`Content::item_encoding`]: crate::openapi::Content::item_encoding
73 #[serde(skip_serializing_if = "Option::is_none", default)]
74 pub item_encoding: Option<Box<Encoding>>,
75
76 /// Optional extensions "x-something"
77 #[serde(skip_serializing_if = "PropMap::is_empty", flatten)]
78 pub extensions: PropMap<String, serde_json::Value>,
79}
80
81impl Encoding {
82 /// Set the content type. See [`Encoding::content_type`].
83 #[must_use]
84 pub fn content_type<S: Into<String>>(mut self, content_type: S) -> Self {
85 self.content_type = Some(content_type.into());
86 self
87 }
88
89 /// Add a [`Header`]. See [`Encoding::headers`].
90 #[must_use]
91 pub fn header<S: Into<String>, H: Into<Header>>(mut self, header_name: S, header: H) -> Self {
92 self.headers.insert(header_name.into(), header.into());
93
94 self
95 }
96
97 /// Set the style [`ParameterStyle`]. See [`Encoding::style`].
98 #[must_use]
99 pub fn style(mut self, style: ParameterStyle) -> Self {
100 self.style = Some(style);
101 self
102 }
103
104 /// Set the explode. See [`Encoding::explode`].
105 #[must_use]
106 pub fn explode(mut self, explode: bool) -> Self {
107 self.explode = Some(explode);
108 self
109 }
110
111 /// Set the allow reserved. See [`Encoding::allow_reserved`].
112 #[must_use]
113 pub fn allow_reserved(mut self, allow_reserved: bool) -> Self {
114 self.allow_reserved = Some(allow_reserved);
115 self
116 }
117
118 /// Add a nested [`Encoding`] by property name. See [`Encoding::encoding`].
119 /// Requires OpenAPI 3.2.
120 #[must_use]
121 pub fn encoding<S: Into<String>, E: Into<Self>>(
122 mut self,
123 property_name: S,
124 encoding: E,
125 ) -> Self {
126 self.encoding.insert(property_name.into(), encoding.into());
127 self
128 }
129
130 /// Set the nested positional encodings. See [`Encoding::prefix_encoding`].
131 /// Requires OpenAPI 3.2.
132 #[must_use]
133 pub fn prefix_encoding<I: IntoIterator<Item = Self>>(mut self, prefix_encoding: I) -> Self {
134 self.prefix_encoding = prefix_encoding.into_iter().collect();
135 self
136 }
137
138 /// Set the nested encoding applied to remaining array items. See [`Encoding::item_encoding`].
139 /// Requires OpenAPI 3.2.
140 #[must_use]
141 pub fn item_encoding<E: Into<Self>>(mut self, item_encoding: E) -> Self {
142 self.item_encoding = Some(Box::new(item_encoding.into()));
143 self
144 }
145
146 /// Add openapi extensions (`x-something`) for [`Encoding`].
147 #[must_use]
148 pub fn extensions(mut self, extensions: PropMap<String, serde_json::Value>) -> Self {
149 self.extensions = extensions;
150 self
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use assert_json_diff::assert_json_eq;
157 use serde_json::json;
158
159 use super::*;
160
161 #[test]
162 fn test_encoding_default() {
163 let encoding = Encoding::default();
164 assert_json_eq!(encoding, json!({}));
165 }
166
167 #[test]
168 fn test_build_encoding() {
169 let encoding = Encoding::default()
170 .content_type("application/json")
171 .header("header1", Header::default())
172 .style(ParameterStyle::Simple)
173 .explode(true)
174 .allow_reserved(false);
175
176 assert_json_eq!(
177 encoding,
178 json!({
179 "contentType": "application/json",
180 "headers": {
181 "header1": {
182 "schema": {
183 "type": "string"
184 }
185 }
186 },
187 "style": "simple",
188 "explode": true,
189 "allowReserved": false
190 })
191 );
192 }
193
194 #[test]
195 fn test_nested_encoding_openapi_3_2() {
196 let encoding = Encoding::default()
197 .content_type("multipart/mixed")
198 .prefix_encoding([Encoding::default().content_type("text/html")])
199 .item_encoding(Encoding::default().content_type("image/*"))
200 .encoding("thumbnail", Encoding::default().content_type("image/png"));
201
202 let value = serde_json::to_value(&encoding).expect("serialize");
203 assert_json_eq!(
204 &value,
205 json!({
206 "contentType": "multipart/mixed",
207 "encoding": { "thumbnail": { "contentType": "image/png" } },
208 "prefixEncoding": [ { "contentType": "text/html" } ],
209 "itemEncoding": { "contentType": "image/*" }
210 })
211 );
212
213 let parsed: Encoding = serde_json::from_value(value).expect("deserialize");
214 assert_eq!(parsed, encoding);
215 }
216}