Add OpenAPI import backend

This commit is contained in:
github-ops committed 2026-06-23 21:03:03 +00:00
1 parent 87cdb95b80
commit a8aa3248c9
34 files changed
+2569 -27

No files matched your search

+234
View File
@@ -0,0 +1,234 @@
use crank_core::HttpMethod;
use serde_json::Value;
use crate::rest::{
model::{RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation},
normalize::{ImportParseError, resolve_local_ref},
recommendations::{document_finding, operation_finding},
};
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
let title = root
.pointer("/info/title")
.and_then(Value::as_str)
.unwrap_or("Imported API")
.to_owned();
let servers = swagger_servers(root);
let mut findings = Vec::new();
if servers.is_empty() {
findings.push(document_finding(
"missing_servers",
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
));
}
let mut operations = Vec::new();
let paths = root
.get("paths")
.and_then(Value::as_object)
.ok_or(ImportParseError::UnsupportedDocument)?;
for (path, path_item) in paths {
let path_parameters = parameters(root, path_item.get("parameters"));
for method_name in ["get", "post", "put", "patch", "delete"] {
let Some(operation_value) = path_item.get(method_name) else {
continue;
};
let Some(method) = method_from_lower(method_name) else {
continue;
};
let mut operation_parameters = path_parameters.clone();
operation_parameters.extend(parameters(root, operation_value.get("parameters")));
let request_body_schema = operation_parameters
.iter()
.find(|parameter| parameter.name == "body")
.and_then(|parameter| parameter.schema.clone());
let operation_parameters = operation_parameters
.into_iter()
.filter(|parameter| parameter.name != "body")
.collect::<Vec<_>>();
operations.push(RestImportOperation {
key: format!("{} {}", method_name.to_uppercase(), path),
method,
path: path.clone(),
operation_id: operation_value
.get("operationId")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
summary: operation_value
.get("summary")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
description: operation_value
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
tags: operation_value
.get("tags")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(ToOwned::to_owned)
.collect()
})
.unwrap_or_default(),
parameters: operation_parameters,
request_body_schema,
response_schema: response_schema(root, operation_value),
servers: Vec::new(),
findings: swagger_operation_findings(path, operation_value),
});
}
}
Ok(RestImportDocument {
format: "swagger".to_owned(),
version: Some("2.0".to_owned()),
title,
servers,
operations,
findings,
})
}
fn swagger_servers(root: &Value) -> Vec<String> {
let Some(host) = root.get("host").and_then(Value::as_str) else {
return Vec::new();
};
let base_path = root.get("basePath").and_then(Value::as_str).unwrap_or("");
let schemes = root
.get("schemes")
.and_then(Value::as_array)
.map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
.filter(|items| !items.is_empty())
.unwrap_or_else(|| vec!["https"]);
schemes
.into_iter()
.map(|scheme| {
format!("{scheme}://{host}{base_path}")
.trim_end_matches('/')
.to_owned()
})
.collect()
}
fn parameters(root: &Value, value: Option<&Value>) -> Vec<RestImportParameter> {
value
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(|item| {
let item = resolve_local_ref(root, item, 0);
let raw_location = item.get("in").and_then(Value::as_str)?;
if raw_location == "body" {
return Some(RestImportParameter {
name: "body".to_owned(),
location: RestParameterLocation::Query,
required: item
.get("required")
.and_then(Value::as_bool)
.unwrap_or(false),
description: item
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
schema: item
.get("schema")
.map(|schema| resolve_local_ref(root, schema, 0)),
});
}
let location = match raw_location {
"path" => RestParameterLocation::Path,
"query" => RestParameterLocation::Query,
"header" => RestParameterLocation::Header,
_ => return None,
};
Some(RestImportParameter {
name: item.get("name").and_then(Value::as_str)?.to_owned(),
location,
required: item
.get("required")
.and_then(Value::as_bool)
.unwrap_or(false)
|| location == RestParameterLocation::Path,
description: item
.get("description")
.and_then(Value::as_str)
.map(ToOwned::to_owned),
schema: swagger_parameter_schema(root, &item),
})
})
.collect()
})
.unwrap_or_default()
}
fn swagger_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
if let Some(schema) = parameter.get("schema") {
return Some(resolve_local_ref(root, schema, 0));
}
let mut schema = serde_json::Map::new();
for key in ["type", "format", "items", "enum", "default", "description"] {
if let Some(value) = parameter.get(key) {
schema.insert(key.to_owned(), resolve_local_ref(root, value, 0));
}
}
if schema.is_empty() {
None
} else {
Some(Value::Object(schema))
}
}
fn response_schema(root: &Value, operation: &Value) -> Option<Value> {
let responses = operation.get("responses")?.as_object()?;
for code in ["200", "201", "202", "default"] {
let Some(response) = responses.get(code) else {
continue;
};
let response = resolve_local_ref(root, response, 0);
if let Some(schema) = response.get("schema") {
return Some(resolve_local_ref(root, schema, 0));
}
}
None
}
fn swagger_operation_findings(
path: &str,
operation: &Value,
) -> Vec<crate::rest::model::ImportFinding> {
let mut findings = Vec::new();
if operation
.get("consumes")
.and_then(Value::as_array)
.is_some_and(|items| {
!items
.iter()
.any(|item| item.as_str().is_some_and(|value| value.contains("json")))
})
{
findings.push(operation_finding(
path,
"unsupported_consumes",
"Метод использует content type без JSON. Проверьте настройки тела запроса после импорта.",
));
}
findings
}
fn method_from_lower(value: &str) -> Option<HttpMethod> {
match value {
"get" => Some(HttpMethod::Get),
"post" => Some(HttpMethod::Post),
"put" => Some(HttpMethod::Put),
"patch" => Some(HttpMethod::Patch),
"delete" => Some(HttpMethod::Delete),
_ => None,
}
}