Skip to main content

salvo_oapi/openapi/
external_docs.rs

1//! Implements [OpenAPI External Docs Object][external_docs] types.
2//!
3//! [external_docs]: https://spec.openapis.org/oas/latest.html#xml-object
4use serde::{Deserialize, Serialize};
5
6use crate::PropMap;
7
8/// Reference of external resource allowing extended documentation.
9#[non_exhaustive]
10#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq)]
11#[serde(rename_all = "camelCase")]
12pub struct ExternalDocs {
13    /// Target url for external documentation location.
14    pub url: String,
15    /// Additional description supporting markdown syntax of the external documentation.
16    pub description: Option<String>,
17
18    /// Optional extensions "x-something"
19    #[serde(skip_serializing_if = "PropMap::is_empty", flatten)]
20    pub extensions: PropMap<String, serde_json::Value>,
21}
22
23impl ExternalDocs {
24    /// Construct a new [`ExternalDocs`].
25    ///
26    /// Function takes target url argument for the external documentation location.
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// # use salvo_oapi::ExternalDocs;
32    /// let external_docs = ExternalDocs::new("https://pet-api.external.docs");
33    /// ```
34    #[must_use]
35    pub fn new<S: AsRef<str>>(url: S) -> Self {
36        Self {
37            url: url.as_ref().to_owned(),
38            ..Default::default()
39        }
40    }
41
42    /// Add target url for external documentation location.
43    #[must_use]
44    pub fn url<I: Into<String>>(mut self, url: I) -> Self {
45        self.url = url.into();
46        self
47    }
48
49    /// Add additional description of external documentation.
50    #[must_use]
51    pub fn description<S: Into<String>>(mut self, description: S) -> Self {
52        self.description = Some(description.into());
53        self
54    }
55
56    /// Add openapi extensions (`x-something`) for [`ExternalDocs`].
57    #[must_use]
58    pub fn extensions(mut self, extensions: PropMap<String, serde_json::Value>) -> Self {
59        self.extensions = extensions;
60        self
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn test_default_external_docs() {
70        let external_docs = ExternalDocs::default();
71        assert_eq!(external_docs.url, "");
72        assert_eq!(external_docs.description, None);
73    }
74
75    #[test]
76    fn test_build_external_docs() {
77        let external_docs = ExternalDocs::default();
78        let external_docs_with_url = external_docs
79            .url("https://pet-api.external.docs")
80            .description("description");
81
82        assert_eq!(external_docs_with_url.url, "https://pet-api.external.docs");
83        assert_eq!(
84            external_docs_with_url.description,
85            Some("description".to_owned())
86        );
87    }
88}