Can generate examples
This commit is contained in:
parent
14c1955b15
commit
208d87df79
40
src/lib.rs
40
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::<HashMap<String, serde_json::Value>>())
|
||||
}
|
||||
|
||||
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::<f64>().expect("Failed to parse f64"))
|
||||
.unwrap_or(1.)),
|
||||
NodeType::Integer => serde_json::json!(self
|
||||
.examples
|
||||
.first()
|
||||
.map(|s| s.parse::<u64>().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()
|
||||
|
@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user