sz_rust_http_facade/
openapi.rs1use thiserror::Error;
6
7#[derive(Debug, Error)]
9pub enum OpenApiError {
10 #[error("OpenAPI build error: {0}")]
12 Build(String),
13 #[error("JSON serialize error: {0}")]
15 Serialize(String),
16}
17
18pub struct OpenApiBuilder {
22 title: String,
23 version: String,
24 description: Option<String>,
25}
26
27impl OpenApiBuilder {
28 pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
30 Self {
31 title: title.into(),
32 version: version.into(),
33 description: None,
34 }
35 }
36
37 pub fn description(mut self, desc: impl Into<String>) -> Self {
39 self.description = Some(desc.into());
40 self
41 }
42
43 pub fn build(self) -> utoipa::openapi::Info {
45 let mut info = utoipa::openapi::Info::default();
46 info.title = self.title;
47 info.version = self.version;
48 info.description = self.description;
49 info
50 }
51
52 pub fn to_json(self) -> Result<String, OpenApiError> {
54 let info = self.build();
55 serde_json::to_string_pretty(&info).map_err(|e| OpenApiError::Serialize(e.to_string()))
56 }
57
58 pub fn validate(self) -> Result<(), OpenApiError> {
60 let info = self.build();
61 if info.title.is_empty() {
62 return Err(OpenApiError::Build("title is empty".into()));
63 }
64 if info.version.is_empty() {
65 return Err(OpenApiError::Build("version is empty".into()));
66 }
67 Ok(())
68 }
69}
70
71#[cfg(feature = "swagger-ui")]
75pub fn swagger_ui_routes() -> axum::Router {
76 utoipa_swagger_ui::SwaggerUi::new("/docs/{_:.*}")
77 .url("/api-docs/openapi.json", utoipa::OpenApi::default())
78 .into()
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn test_openapi_build() {
87 let info = OpenApiBuilder::new("Test API", "1.0.0").build();
88 assert_eq!(info.title, "Test API");
89 assert_eq!(info.version, "1.0.0");
90 }
91
92 #[test]
93 fn test_openapi_to_json() {
94 let json = OpenApiBuilder::new("Test API", "1.0.0").to_json().unwrap();
95 assert!(json.contains("Test API"));
96 assert!(json.contains("1.0.0"));
97 }
98
99 #[test]
100 fn test_openapi_validate() {
101 let result = OpenApiBuilder::new("Test", "1.0").validate();
102 assert!(result.is_ok());
103 }
104
105 #[test]
106 fn test_openapi_validate_empty_title() {
107 let result = OpenApiBuilder::new("", "1.0").validate();
108 assert!(result.is_err());
109 }
110
111 #[test]
112 fn test_openapi_error_display() {
113 let err = OpenApiError::Build("test error".into());
114 assert_eq!(err.to_string(), "OpenAPI build error: test error");
115 }
116}