use serde::Serialize;
use std::fs;
use crate::{
Draft,
Result,
Schematic,
};
mod defs;
pub mod r#type;
pub use defs::Definitions;
pub use r#type::Type;
#[derive(Debug, Serialize)]
pub struct Schema {
#[serde(rename = "$schema")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<Draft>,
#[serde(rename = "$id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub title: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(flatten)]
ty: Type,
#[serde(rename = "$defs")]
#[serde(skip_serializing_if = "Definitions::is_empty")]
defs: Definitions,
}
impl Schema {
pub fn new<T: Schematic>(title: &str) -> Self {
Schema {
schema: None,
id: None,
title: title.into(),
description: None,
ty: T::__type_no_attr(),
defs: T::__defs(),
}
}
pub fn description(
&mut self,
description: impl Into<String>,
) -> &mut Self {
self.description = Some(description.into());
self
}
pub fn schema(
&mut self,
schema: Draft,
) -> &mut Self {
self.schema = Some(schema);
self
}
pub fn id(
&mut self,
id: impl Into<String>,
) -> &mut Self {
self.id = Some(id.into());
self
}
pub fn to_string(&self) -> Result<String> {
let schema_str = serde_json::to_string(self)?;
Ok(schema_str)
}
pub fn to_string_pretty(&self) -> Result<String> {
let schema_str = serde_json::to_string_pretty(self)?;
Ok(schema_str)
}
pub fn write(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<()> {
let schema_str = self.to_string()?;
fs::write(path, schema_str)?;
Ok(())
}
pub fn write_pretty(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<()> {
let schema_str = self.to_string_pretty()?;
fs::write(path, schema_str)?;
Ok(())
}
}