salvo_oapi/openapi/
header.rs

1//! Implements [OpenAPI Header Object][header] types.
2//!
3//! [header]: https://spec.openapis.org/oas/latest.html#header-object
4
5use serde::{Deserialize, Serialize};
6
7use super::{BasicType, Object, RefOr, Schema};
8
9/// Implements [OpenAPI Header Object][header] for response headers.
10///
11/// [header]: https://spec.openapis.org/oas/latest.html#header-object
12#[non_exhaustive]
13#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
14pub struct Header {
15    /// Schema of header type.
16    pub schema: RefOr<Schema>,
17
18    /// Additional description of the header value.
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub description: Option<String>,
21}
22
23impl Header {
24    /// Construct a new [`Header`] with custom schema. If you wish to construct a default
25    /// header with `String` type you can use [`Header::default`] function.
26    ///
27    /// # Examples
28    ///
29    /// Create new [`Header`] with integer type.
30    /// ```
31    /// # use salvo_oapi::{Header, Object, BasicType};
32    /// let header = Header::new(Object::with_type(BasicType::Integer));
33    /// ```
34    ///
35    /// Create a new [`Header`] with default type `String`
36    /// ```
37    /// # use salvo_oapi::Header;
38    /// let header = Header::default();
39    /// ```
40    pub fn new<C: Into<RefOr<Schema>>>(component: C) -> Self {
41        Self {
42            schema: component.into(),
43            ..Default::default()
44        }
45    }
46    /// Add schema of header.
47    pub fn schema<I: Into<RefOr<Schema>>>(mut self, component: I) -> Self {
48        self.schema = component.into();
49        self
50    }
51
52    /// Add additional description for header.
53    pub fn description<S: Into<String>>(mut self, description: S) -> Self {
54        self.description = Some(description.into());
55        self
56    }
57}
58
59impl Default for Header {
60    fn default() -> Self {
61        Self {
62            description: Default::default(),
63            schema: Object::with_type(BasicType::String).into(),
64        }
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use assert_json_diff::assert_json_eq;
71    use serde_json::json;
72
73    use super::*;
74
75    #[test]
76    fn test_build_header() {
77        let header = Header::new(Object::with_type(BasicType::String));
78        assert_json_eq!(
79            header,
80            json!({
81                "schema": {
82                    "type": "string"
83                }
84            })
85        );
86
87        let header = header
88            .description("test description")
89            .schema(Object::with_type(BasicType::Number));
90        assert_json_eq!(
91            header,
92            json!({
93                "description": "test description",
94                "schema": {
95                    "type": "number"
96                }
97            })
98        );
99    }
100}