From 208d87df794730d5b63d7a6cf2faf9b25365bdde Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Tue, 28 Feb 2023 15:56:35 +0100 Subject: [PATCH] Can generate examples --- src/lib.rs | 40 +++++++++++++++++++++++++++++++++++++++- src/main.rs | 6 ++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 539c308..8c6f467 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ use okapi::openapi3::{Components, OpenApi, SchemaObject}; use okapi::schemars::schema::{InstanceType, Schema, SingleOrVec}; -use serde_json::Value; +use serde_json::{json, Value}; +use std::collections::HashMap; fn recurse_fix(mut v: &mut Value) { match &mut v { @@ -209,6 +210,43 @@ impl TreeNode { } } + /// Get JSON example value + pub fn example_value(&self) -> 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::Object { children, .. } => { + json!(children + .iter() + .map(|c| (c.name.clone(), c.node.example_value())) + .collect::>()) + } + + NodeType::String => Value::String( + self.examples + .first() + .map(|s| s.as_str().trim_matches('"')) + .unwrap_or("string") + .to_string(), + ), + NodeType::Number => serde_json::json!(self + .examples + .first() + .map(|s| s.parse::().expect("Failed to parse f64")) + .unwrap_or(1.)), + NodeType::Integer => serde_json::json!(self + .examples + .first() + .map(|s| s.parse::().expect("Failed to parse f64")) + .unwrap_or(0)), + } + } + /// Turn object into JSON schema pub fn json_schema(&self) -> Value { valico::json_schema::builder::schema(|s| self.json_schema_inner(s)).into_json() diff --git a/src/main.rs b/src/main.rs index 91818d5..94e1968 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,6 +37,9 @@ enum Action { /// Dump JSON schema JsonSchema, + /// Dump JSON example + JsonExample, + /// Dump as Graphviz graph Graph, @@ -80,6 +83,9 @@ 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()) + } } }