diff --git a/src/lib.rs b/src/lib.rs index 8c6f467..b502c65 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,8 @@ use okapi::schemars::schema::{InstanceType, Schema, SingleOrVec}; use serde_json::{json, Value}; use std::collections::HashMap; +pub const REF_OBJECT: &str = "\u{0}\u{0}\u{0}\u{0}"; + fn recurse_fix(mut v: &mut Value) { match &mut v { Value::Array(array) => { @@ -211,19 +213,23 @@ impl TreeNode { } /// Get JSON example value - pub fn example_value(&self) -> Value { + pub fn example_value(&self, max_recursion: usize) -> Value { match &self.r#type { NodeType::Null => Value::Null, NodeType::Boolean => { Value::Bool(self.examples.first().map(|e| e == "true").unwrap_or(false)) } - NodeType::Array { item } => Value::Array(vec![item.example_value()]), + NodeType::Array { item } => Value::Array(vec![item.example_value(max_recursion)]), NodeType::Object { children, .. } => { + if max_recursion == 0 { + return json!(HashMap::from([(REF_OBJECT.to_string(), &self.name)])); + } + json!(children .iter() - .map(|c| (c.name.clone(), c.node.example_value())) + .map(|c| (c.name.clone(), c.node.example_value(max_recursion - 1))) .collect::>()) } diff --git a/src/main.rs b/src/main.rs index 94e1968..cab9b9c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use clap::{Parser, Subcommand}; use openapi_parser::{ build_tree, parse_schema, parse_schema_fix_example_issue, NodeType, ObjectChild, TreeNode, + REF_OBJECT, }; use std::collections::HashSet; use std::fmt::Write; @@ -38,7 +39,11 @@ enum Action { JsonSchema, /// Dump JSON example - JsonExample, + JsonExample { + /// Maximum recursion in dump + #[arg(short, long, default_value_t = 100)] + max_recursion: usize, + }, /// Dump as Graphviz graph Graph, @@ -83,8 +88,11 @@ fn main() { Action::Graph => println!("{}", graphviz_export(&tree)), Action::Tex { .. } => println!("{}", tex_export(&tree)), Action::JsonSchema => println!("{}", json_schema(&tree)), - Action::JsonExample => { - println!("{}", serde_json::to_string(&tree.example_value()).unwrap()) + Action::JsonExample { max_recursion } => { + println!( + "{}", + serde_json::to_string(&tree.example_value(max_recursion)).unwrap() + ) } } } @@ -226,6 +234,13 @@ fn tex_export(tree: &TreeNode) -> String { ); } out.push_str("\\end{schemaprops}\n"); + + // JSON export + out.push_str("\\begin{jsonsample}\n"); + let json_doc = serde_json::to_string_pretty(&tree.example_value(1)).unwrap(); + let replace_key = serde_json::to_string(REF_OBJECT).unwrap(); + out.push_str(&json_doc.replace(&format!("{replace_key}:"), "$ref")); + out.push_str("\n\\end{jsonsample}\n"); } _ => tex_export_inner( &ObjectChild {