use serde_json::{Map, Value};
use crate::error::Error;
use crate::options::ResolvedOptions;
use crate::schema::convert_from_schema;
use crate::value::is_truthy;
pub(crate) fn convert_from_parameter(
parameter: Value,
options: &ResolvedOptions,
) -> Result<Value, Error> {
let object = match ¶meter {
Value::Object(map) => map,
_ => &Map::new(),
};
let description = object.get("description").cloned();
if let Some(schema) = object.get("schema") {
if is_truthy(schema) {
return convert_parameter_schema(schema.clone(), description, options);
}
}
if let Some(content) = object.get("content") {
if is_truthy(content) {
return convert_from_contents(content, description, options);
}
}
if options.strict_mode {
return Err(Error::InvalidInput(
"OpenAPI parameter must have either a 'schema' or a 'content' property".to_string(),
));
}
convert_parameter_schema(Value::Object(Map::new()), description, options)
}
fn convert_parameter_schema(
schema: Value,
description: Option<Value>,
options: &ResolvedOptions,
) -> Result<Value, Error> {
let schema = if is_truthy(&schema) {
schema
} else {
Value::Object(Map::new())
};
let mut json_schema = convert_from_schema(schema, options)?;
if let Some(desc) = description {
if is_truthy(&desc) {
if let Value::Object(map) = &mut json_schema {
map.insert("description".to_string(), desc);
}
}
}
Ok(json_schema)
}
fn convert_from_contents(
content: &Value,
description: Option<Value>,
options: &ResolvedOptions,
) -> Result<Value, Error> {
let mut schemas = Map::new();
if let Value::Object(content_map) = content {
for (mime, entry) in content_map {
let schema = match entry {
Value::Object(m) => m.get("schema").cloned().unwrap_or(Value::Null),
_ => Value::Null,
};
let converted = convert_parameter_schema(schema, description.clone(), options)?;
schemas.insert(mime.clone(), converted);
}
}
Ok(Value::Object(schemas))
}