use aylis_core::{PropKind, RecordInfo};
use serde_json::Value as Json;
pub const MASTER_FIELD_RECORD: RecordInfo =
RecordInfo { name: "MasterField", fields: &[("field", PropKind::String), ("master_field", PropKind::String)] };
pub const INDEX_DEF_RECORD: RecordInfo = RecordInfo { name: "IndexDef", fields: &[("name", PropKind::String), ("fields", PropKind::String)] };
pub const FILTER_PARAM_RECORD: RecordInfo = RecordInfo { name: "FilterParam", fields: &[("name", PropKind::String), ("value", PropKind::String)] };
fn items(text: &str) -> Vec<Json> {
match serde_json::from_str::<Json>(text) {
Ok(Json::Array(items)) => items,
_ => Vec::new(),
}
}
fn text(json: &Json, key: &str) -> String {
match &json[key] {
Json::String(s) => s.trim().to_string(),
Json::Null => String::new(),
other => other.to_string(),
}
}
pub(crate) fn master_fields(spec: &str) -> Vec<(String, String)> {
items(spec)
.iter()
.filter_map(|j| {
let field = text(j, "field");
if field.is_empty() {
return None;
}
let master = text(j, "master_field");
let master = if master.is_empty() { field.clone() } else { master };
Some((field, master))
})
.collect()
}
pub(crate) fn index_defs(spec: &str) -> Vec<(String, String)> {
items(spec).iter().map(|j| (text(j, "name"), text(j, "fields"))).filter(|(n, _)| !n.is_empty()).collect()
}
pub(crate) fn filter_params(spec: &str) -> Vec<(String, String)> {
items(spec).iter().map(|j| (text(j, "name"), text(j, "value"))).filter(|(n, _)| !n.is_empty()).collect()
}