use serde_json::{Map, Value, json};
use crate::router::{Method, RouteInfo};
pub type SchemaFn = fn() -> Value;
#[derive(Debug, Clone, Copy)]
pub struct ResponseSpec {
pub status: u16,
pub schema: Option<SchemaFn>,
}
#[derive(Debug, Clone)]
pub struct Operation {
pub summary: Option<&'static str>,
pub tag: Option<&'static str>,
pub body: Option<SchemaFn>,
pub responses: Vec<ResponseSpec>,
}
impl Operation {
pub fn new() -> Self {
Self {
summary: None,
tag: None,
body: None,
responses: Vec::new(),
}
}
}
impl Default for Operation {
fn default() -> Self {
Self::new()
}
}
fn describe(status: u16) -> &'static str {
match status {
200 => "OK",
201 => "Created",
202 => "Accepted",
204 => "No content",
400 => "The request could not be read",
401 => "Unauthenticated",
403 => "Forbidden",
404 => "Not found",
409 => "Conflict",
422 => "The given data was invalid",
429 => "Too many requests",
500 => "Internal server error",
_ => "Response",
}
}
fn problem_schema() -> Value {
json!({
"type": "object",
"title": "Problem",
"description": "An RFC 7807 problem document.",
"properties": {
"type": { "type": "string", "format": "uri" },
"title": { "type": "string" },
"status": { "type": "integer" },
"errors": {
"type": "object",
"description": "Field-keyed validation messages, present on 422 responses.",
"additionalProperties": { "type": "array", "items": { "type": "string" } }
}
},
"required": ["type", "title", "status"]
})
}
fn is_error(status: u16) -> bool {
status >= 400
}
fn path_parameters(path: &str) -> Vec<Value> {
let mut parameters = Vec::new();
let mut rest = path;
while let Some(start) = rest.find('{') {
let Some(end) = rest[start..].find('}') else {
break;
};
let name = &rest[start + 1..start + end];
if !name.is_empty() {
parameters.push(json!({
"name": name,
"in": "path",
"required": true,
"schema": { "type": "string" }
}));
}
rest = &rest[start + end + 1..];
}
parameters
}
fn method_key(method: Method) -> &'static str {
match method {
Method::Get => "get",
Method::Post => "post",
Method::Put => "put",
Method::Patch => "patch",
Method::Delete => "delete",
}
}
pub fn document(title: &str, version: &str, routes: &[RouteInfo]) -> Value {
let mut paths: Map<String, Value> = Map::new();
for route in routes {
let entry = paths.entry(route.path.clone()).or_insert_with(|| json!({}));
let Some(entry) = entry.as_object_mut() else {
continue;
};
entry.insert(method_key(route.method).to_owned(), operation_object(route));
}
json!({
"openapi": "3.1.0",
"info": { "title": title, "version": version },
"paths": Value::Object(paths),
"components": { "schemas": { "Problem": problem_schema() } }
})
}
fn operation_object(route: &RouteInfo) -> Value {
let mut object = Map::new();
object.insert("operationId".to_owned(), json!(route.action));
let parameters = path_parameters(&route.path);
if !parameters.is_empty() {
object.insert("parameters".to_owned(), json!(parameters));
}
let Some(operation) = &route.operation else {
object.insert(
"responses".to_owned(),
json!({ "default": { "description": "Undocumented" } }),
);
return Value::Object(object);
};
if let Some(summary) = operation.summary {
object.insert("summary".to_owned(), json!(summary));
}
if let Some(tag) = operation.tag {
object.insert("tags".to_owned(), json!([tag]));
}
if let Some(body) = operation.body {
object.insert(
"requestBody".to_owned(),
json!({
"required": true,
"content": { "application/json": { "schema": body() } }
}),
);
}
let mut responses = Map::new();
for response in &operation.responses {
let mut entry = json!({ "description": describe(response.status) });
let entry_object = entry.as_object_mut().expect("just built as an object");
if let Some(schema) = response.schema {
entry_object.insert(
"content".to_owned(),
json!({ "application/json": { "schema": schema() } }),
);
} else if is_error(response.status) {
entry_object.insert(
"content".to_owned(),
json!({
"application/problem+json": {
"schema": { "$ref": "#/components/schemas/Problem" }
}
}),
);
}
responses.insert(response.status.to_string(), entry);
}
if responses.is_empty() {
responses.insert(
"default".to_owned(),
json!({ "description": "Undocumented" }),
);
}
object.insert("responses".to_owned(), Value::Object(responses));
Value::Object(object)
}
#[cfg(test)]
mod tests {
use super::*;
fn schema() -> Value {
json!({ "type": "object", "properties": { "id": { "type": "integer" } } })
}
fn route(method: Method, path: &str, operation: Option<Operation>) -> RouteInfo {
RouteInfo {
method,
path: path.to_owned(),
action: "PostsController::show",
middleware: 0,
operation,
}
}
#[test]
fn derives_path_parameters_from_the_pattern() {
let parameters = path_parameters("/teams/{team}/posts/{id}");
assert_eq!(parameters.len(), 2);
assert_eq!(parameters[0]["name"], "team");
assert_eq!(parameters[1]["name"], "id");
assert_eq!(parameters[1]["in"], "path");
}
#[test]
fn a_path_without_parameters_declares_none() {
assert!(path_parameters("/posts").is_empty());
}
#[test]
fn an_unclosed_brace_does_not_hang_or_panic() {
assert!(path_parameters("/posts/{id").is_empty());
}
#[test]
fn documents_a_described_operation() {
let operation = Operation {
summary: Some("Show a post"),
tag: Some("posts"),
body: None,
responses: vec![
ResponseSpec {
status: 200,
schema: Some(schema),
},
ResponseSpec {
status: 404,
schema: None,
},
],
};
let document = document(
"Test",
"0.1.0",
&[route(Method::Get, "/posts/{id}", Some(operation))],
);
let get = &document["paths"]["/posts/{id}"]["get"];
assert_eq!(document["openapi"], "3.1.0");
assert_eq!(get["summary"], "Show a post");
assert_eq!(get["tags"][0], "posts");
assert_eq!(get["operationId"], "PostsController::show");
assert_eq!(
get["responses"]["200"]["content"]["application/json"]["schema"],
schema()
);
assert_eq!(get["responses"]["404"]["description"], "Not found");
assert_eq!(
get["responses"]["404"]["content"]["application/problem+json"]["schema"]["$ref"],
"#/components/schemas/Problem"
);
}
#[test]
fn a_request_body_is_marked_required() {
let operation = Operation {
body: Some(schema),
responses: vec![ResponseSpec {
status: 201,
schema: Some(schema),
}],
..Operation::new()
};
let document = document(
"Test",
"0.1.0",
&[route(Method::Post, "/posts", Some(operation))],
);
let post = &document["paths"]["/posts"]["post"];
assert_eq!(post["requestBody"]["required"], true);
assert_eq!(
post["requestBody"]["content"]["application/json"]["schema"],
schema()
);
assert_eq!(post["responses"]["201"]["description"], "Created");
}
#[test]
fn an_undocumented_route_still_appears() {
let document = document("Test", "0.1.0", &[route(Method::Get, "/health", None)]);
assert_eq!(
document["paths"]["/health"]["get"]["responses"]["default"]["description"],
"Undocumented"
);
}
#[test]
fn methods_on_one_path_share_an_entry() {
let document = document(
"Test",
"0.1.0",
&[
route(Method::Get, "/posts", None),
route(Method::Post, "/posts", None),
],
);
let entry = document["paths"]["/posts"].as_object().expect("object");
assert!(entry.contains_key("get") && entry.contains_key("post"));
}
}