use super::context::{LoadContext, SaveContext};
use super::model_options::ModelOptions;
#[derive(Debug, Clone, Default)]
pub struct Model {
pub id: String,
pub provider: Option<String>,
pub api_type: Option<String>,
pub connection: serde_json::Value,
pub options: Option<ModelOptions>,
}
impl Model {
pub fn new() -> Self {
Self::default()
}
pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
let value: serde_json::Value = serde_json::from_str(json)?;
Ok(Self::load_from_value(&value, ctx))
}
pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
let value: serde_json::Value = serde_yaml::from_str(yaml)?;
Ok(Self::load_from_value(&value, ctx))
}
pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
let value = ctx.process_input(value.clone());
if let Some(s) = value.as_str() {
let value = s.to_string();
let expansion = serde_json::json!({"id":value});
return Self::load_from_value(&expansion, ctx);
}
Self {
id: value
.get("id")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string(),
provider: value
.get("provider")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
api_type: value
.get("apiType")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
connection: value
.get("connection")
.cloned()
.unwrap_or(serde_json::Value::Null),
options: value
.get("options")
.filter(|v| v.is_object() || v.is_array() || v.is_string())
.map(|v| ModelOptions::load_from_value(v, ctx)),
}
}
pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
let mut result = serde_json::Map::new();
if !self.id.is_empty() {
result.insert("id".to_string(), serde_json::Value::String(self.id.clone()));
}
if let Some(ref val) = self.provider {
result.insert(
"provider".to_string(),
serde_json::Value::String(val.clone()),
);
}
if let Some(ref val) = self.api_type {
result.insert(
"apiType".to_string(),
serde_json::Value::String(val.clone()),
);
}
if !self.connection.is_null() {
result.insert("connection".to_string(), self.connection.clone());
}
if let Some(ref val) = self.options {
let nested = val.to_value(ctx);
if !nested.is_null() {
result.insert("options".to_string(), nested);
}
}
ctx.process_dict(serde_json::Value::Object(result))
}
pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(&self.to_value(ctx))
}
pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
serde_yaml::to_string(&self.to_value(ctx))
}
}