use std::sync::Arc;
use hyper::Method;
use crate::validation::InputSchemas;
pub(crate) mod doc;
#[cfg(feature = "openapi")]
pub(crate) mod docs;
#[cfg(feature = "openapi")]
pub(crate) mod output;
#[cfg(feature = "openapi")]
pub(crate) mod spec;
#[cfg(feature = "swagger")]
pub(crate) mod ui;
#[derive(Debug, Clone)]
#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
pub(crate) struct RouteMeta {
pub(crate) method: Method,
pub(crate) path: String,
pub(crate) doc: Option<doc::RouteDoc>,
pub(crate) input: Option<Arc<InputSchemas>>,
pub(crate) operation_id: String,
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
pub(crate) struct AppMeta {
pub(crate) api: Option<doc::ApiDoc>,
pub(crate) routes: Vec<RouteMeta>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PathParam {
pub(crate) name: String,
pub(crate) catch_all: bool,
}
pub(crate) fn to_openapi_path(path: &str) -> Result<(String, Vec<PathParam>), String> {
let mut params: Vec<PathParam> = Vec::new();
let segments: Vec<&str> = path.split('/').collect();
let last = segments.len() - 1;
let mut out = Vec::with_capacity(segments.len());
for (i, seg) in segments.iter().enumerate() {
let (name, catch_all) = match *seg {
"*" if i == last => ("splat".to_string(), true),
s if s.starts_with(':') && s.len() > 1 => (s[1..].to_string(), false),
s if s.starts_with('*') && s.len() > 1 && i == last => (s[1..].to_string(), true),
s => {
out.push(s.to_string());
continue;
}
};
if params.iter().any(|p| p.name == name) {
return Err(format!(
"route path `{path}` names the parameter `{name}` twice"
));
}
out.push(format!("{{{name}}}"));
params.push(PathParam { name, catch_all });
}
Ok((out.join("/"), params))
}
pub(crate) fn default_operation_id(method: &Method, path: &str) -> String {
let template = to_openapi_path(path)
.map(|(template, _)| template)
.unwrap_or_else(|_| path.to_string());
let mut slug = String::new();
for c in template.chars() {
match c {
c if c.is_ascii_alphanumeric() => slug.push(c.to_ascii_lowercase()),
_ if slug.ends_with('_') || slug.is_empty() => {}
_ => slug.push('_'),
}
}
let slug = slug.trim_end_matches('_');
let method = method.as_str().to_ascii_lowercase();
if slug.is_empty() {
format!("{method}_root")
} else {
format!("{method}_{slug}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn route_patterns_convert_to_openapi_templates() {
for (given, expected, names) in [
("/", "/", vec![]),
("/users/:id", "/users/{id}", vec![("id", false)]),
(
"/users/:id/posts/:post",
"/users/{id}/posts/{post}",
vec![("id", false), ("post", false)],
),
("/files/*", "/files/{splat}", vec![("splat", true)]),
("/files/*rest", "/files/{rest}", vec![("rest", true)]),
] {
let (path, params) = to_openapi_path(given).expect(given);
assert_eq!(path, expected);
let got: Vec<(&str, bool)> = params
.iter()
.map(|p| (p.name.as_str(), p.catch_all))
.collect();
assert_eq!(got, names, "{given}");
}
let err = to_openapi_path("/a/:x/b/:x").expect_err("duplicate");
assert!(err.contains("`x` twice"), "{err}");
}
#[test]
fn operation_ids_are_slugs_of_method_and_path() {
assert_eq!(
default_operation_id(&Method::GET, "/api/notes/:id"),
"get_api_notes_id"
);
assert_eq!(default_operation_id(&Method::POST, "/"), "post_root");
assert_eq!(default_operation_id(&Method::GET, "/*"), "get_splat");
assert_eq!(default_operation_id(&Method::GET, "/files"), "get_files");
assert_eq!(
default_operation_id(&Method::DELETE, "/Files/*rest"),
"delete_files_rest"
);
assert_eq!(
default_operation_id(&Method::GET, "/a--b/c.d"),
"get_a_b_c_d"
);
}
}