1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use poem::{
    endpoint::{make_sync, BoxEndpoint},
    web::cookie::CookieKey,
    Endpoint, EndpointExt, IntoEndpoint, Response, Route,
};

#[cfg(feature = "swagger-ui")]
use crate::ui::create_ui_endpoint;
use crate::{
    poem::middleware::CookieJarManager,
    registry::{Document, MetaInfo, MetaServer, Registry},
    OpenApi,
};

/// An OpenAPI service for Poem.
pub struct OpenApiService<T> {
    api: T,
    info: Option<MetaInfo>,
    servers: Vec<MetaServer>,
    cookie_key: Option<CookieKey>,
}

impl<T> OpenApiService<T> {
    /// Create an OpenAPI container.
    #[must_use]
    pub fn new(api: T) -> Self {
        Self {
            api,
            info: None,
            servers: Vec::new(),
            cookie_key: None,
        }
    }

    /// Sets the title of the API container.
    ///
    /// Reference: <https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#infoObject>
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.info.get_or_insert_with(Default::default).title = Some(title.into());
        self
    }

    /// Sets the description of the API container.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.info.get_or_insert_with(Default::default).description = Some(description.into());
        self
    }

    /// Sets the version of the API container.
    ///
    /// NOTE: The version of the OpenAPI document (which is distinct from the
    /// OpenAPI Specification version or the API implementation version).
    ///
    /// Reference: <https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#infoObject>
    #[must_use]
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.info.get_or_insert_with(Default::default).version = Some(version.into());
        self
    }

    /// Appends a server to the API container.
    ///
    /// Reference: <https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverObject>
    #[must_use]
    pub fn server(mut self, url: impl Into<String>) -> Self {
        self.servers.push(MetaServer {
            url: url.into(),
            description: None,
        });
        self
    }

    /// Appends a server and description to the API container.
    #[must_use]
    pub fn server_with_description(
        mut self,
        url: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        self.servers.push(MetaServer {
            url: url.into(),
            description: Some(description.into()),
        });
        self
    }

    /// Sets the cookie key.
    pub fn cookie_key(self, key: CookieKey) -> Self {
        Self {
            cookie_key: Some(key),
            ..self
        }
    }

    /// Create the Swagger UI endpoint.
    #[must_use]
    #[cfg(feature = "swagger-ui")]
    pub fn swagger_ui(&self) -> impl Endpoint
    where
        T: OpenApi,
    {
        create_ui_endpoint(&self.spec())
    }

    /// Create an endpoint to serve the open api specification.
    pub fn spec_endpoint(&self) -> impl Endpoint
    where
        T: OpenApi,
    {
        let spec = self.spec();
        make_sync(move |_| {
            Response::builder()
                .content_type("application/json")
                .body(spec.clone())
        })
    }

    /// Returns the OAS specification file.
    pub fn spec(&self) -> String
    where
        T: OpenApi,
    {
        let mut registry = Registry::new();
        let metadata = T::meta();
        T::register(&mut registry);

        let doc = Document {
            info: self.info.as_ref(),
            servers: &self.servers,
            apis: &metadata,
            registry: &registry,
        };
        serde_json::to_string_pretty(&doc).unwrap()
    }
}

impl<T: OpenApi> IntoEndpoint for OpenApiService<T> {
    type Endpoint = BoxEndpoint<'static, Response>;

    fn into_endpoint(self) -> Self::Endpoint {
        match self.cookie_key {
            Some(key) => self
                .api
                .add_routes(Route::new())
                .with(CookieJarManager::with_key(key))
                .boxed(),
            None => self
                .api
                .add_routes(Route::new())
                .with(CookieJarManager::new())
                .boxed(),
        }
    }
}