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
use poem::{endpoint::BoxEndpoint, route, Endpoint, EndpointExt, IntoEndpoint, Response};
use crate::{
registry::{Document, MetaInfo, MetaServer, Registry},
ui::create_ui_endpoint,
OpenApi,
};
pub struct OpenApiService<T> {
api: T,
info: Option<MetaInfo>,
servers: Vec<MetaServer>,
}
impl<T> OpenApiService<T> {
#[must_use]
pub fn new(api: T) -> Self {
Self {
api,
info: None,
servers: Vec::new(),
}
}
#[must_use]
pub fn title(mut self, title: &'static str) -> Self {
self.info.get_or_insert_with(Default::default).title = Some(title);
self
}
#[must_use]
pub fn description(mut self, description: &'static str) -> Self {
self.info.get_or_insert_with(Default::default).description = Some(description);
self
}
#[must_use]
pub fn version(mut self, version: &'static str) -> Self {
self.info.get_or_insert_with(Default::default).version = Some(version);
self
}
#[must_use]
pub fn server(mut self, url: &'static str) -> Self {
self.servers.push(MetaServer {
url,
description: None,
});
self
}
#[must_use]
pub fn server_with_description(mut self, url: &'static str, description: &'static str) -> Self {
self.servers.push(MetaServer {
url,
description: Some(description),
});
self
}
#[must_use]
pub fn swagger_ui(&self, absolute_uri: impl AsRef<str>) -> impl Endpoint
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: ®istry,
};
let doc_json = serde_json::to_string_pretty(&doc).unwrap();
create_ui_endpoint(absolute_uri.as_ref(), &doc_json)
}
}
impl<T: OpenApi> IntoEndpoint for OpenApiService<T> {
type Endpoint = BoxEndpoint<Response>;
fn into_endpoint(self) -> Self::Endpoint {
self.api.add_routes(route()).boxed()
}
}