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    #[must_use]
58    pub fn content_type<S: Into<String>>(mut self, content_type: S) -> Self {
59        self.content_type = Some(content_type.into());
60        self
61    }
62
63    /// Add a [`Header`]. See [`Encoding::headers`].
64    #[must_use]
65    pub fn header<S: Into<String>, H: Into<Header>>(mut self, header_name: S, header: H) -> Self {
66        self.headers.insert(header_name.into(), header.into());
67
68        self
69    }
70
71    /// Set the style [`ParameterStyle`]. See [`Encoding::style`].
72    #[must_use]
73    pub fn style(mut self, style: ParameterStyle) -> Self {
74        self.style = Some(style);
75        self
76    }
77
78    /// Set the explode. See [`Encoding::explode`].
79    #[must_use]
80    pub fn explode(mut self, explode: bool) -> Self {
81        self.explode = Some(explode);
82        self
83    }
84
85    /// Set the allow reserved. See [`Encoding::allow_reserved`].
86    #[must_use]
87    pub fn allow_reserved(mut self, allow_reserved: bool) -> Self {
88        self.allow_reserved = Some(allow_reserved);
89        self
90    }
91
92    /// Add openapi extensions (`x-something`) for [`Encoding`].
93    #[must_use]
94    pub fn extensions(mut self, extensions: PropMap<String, serde_json::Value>) -> Self {
95        self.extensions = extensions;
96        self
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use assert_json_diff::assert_json_eq;
103    use serde_json::json;
104
105    use super::*;
106
107    #[test]
108    fn test_encoding_default() {
109        let encoding = Encoding::default();
110        assert_json_eq!(encoding, json!({}));
111    }
112
113    #[test]
114    fn test_build_encoding() {
115        let encoding = Encoding::default()
116            .content_type("application/json")
117            .header("header1", Header::default())
118            .style(ParameterStyle::Simple)
119            .explode(true)
120            .allow_reserved(false);
121
122        assert_json_eq!(
123            encoding,
124            json!({
125              "contentType": "application/json",
126              "headers": {
127                "header1": {
128                  "schema": {
129                    "type": "string"
130                  }
131                }
132              },
133              "style": "simple",
134              "explode": true,
135              "allowReserved": false
136            })
137        );
138    }
139}