Skip to main content

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(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    /// Determines whether the parameter value SHOULD allow reserved characters, as defined by
44    /// RFC3986 `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is
45    /// false. This property SHALL be ignored if the request body media type is not
46    /// `application/x-www-form-urlencoded`.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub allow_reserved: Option<bool>,
49
50    /// Optional extensions "x-something"
51    #[serde(skip_serializing_if = "PropMap::is_empty", flatten)]
52    pub extensions: PropMap<String, serde_json::Value>,
53}
54
55impl Encoding {
56    /// Set the content type. See [`Encoding::content_type`].
57    pub fn content_type<S: Into<String>>(mut self, content_type: S) -> Self {
58        self.content_type = Some(content_type.into());
59        self
60    }
61
62    /// Add a [`Header`]. See [`Encoding::headers`].
63    pub fn header<S: Into<String>, H: Into<Header>>(mut self, header_name: S, header: H) -> Self {
64        self.headers.insert(header_name.into(), header.into());
65
66        self
67    }
68
69    /// Set the style [`ParameterStyle`]. See [`Encoding::style`].
70    pub fn style(mut self, style: ParameterStyle) -> Self {
71        self.style = Some(style);
72        self
73    }
74
75    /// Set the explode. See [`Encoding::explode`].
76    pub fn explode(mut self, explode: bool) -> Self {
77        self.explode = Some(explode);
78        self
79    }
80
81    /// Set the allow reserved. See [`Encoding::allow_reserved`].
82    pub fn allow_reserved(mut self, allow_reserved: bool) -> Self {
83        self.allow_reserved = Some(allow_reserved);
84        self
85    }
86
87    /// Add openapi extensions (`x-something`) for [`Encoding`].
88    pub fn extensions(mut self, extensions: PropMap<String, serde_json::Value>) -> Self {
89        self.extensions = extensions;
90        self
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use assert_json_diff::assert_json_eq;
97    use serde_json::json;
98
99    use super::*;
100
101    #[test]
102    fn test_encoding_default() {
103        let encoding = Encoding::default();
104        assert_json_eq!(encoding, json!({}));
105    }
106
107    #[test]
108    fn test_build_encoding() {
109        let encoding = Encoding::default()
110            .content_type("application/json")
111            .header("header1", Header::default())
112            .style(ParameterStyle::Simple)
113            .explode(true)
114            .allow_reserved(false);
115
116        assert_json_eq!(
117            encoding,
118            json!({
119              "contentType": "application/json",
120              "headers": {
121                "header1": {
122                  "schema": {
123                    "type": "string"
124                  }
125                }
126              },
127              "style": "simple",
128              "explode": true,
129              "allowReserved": false
130            })
131        );
132    }
133}