use crate::core::messages::serializer::ButtplugSerializerError;
use serde_json::Value;
use valico::json_schema;
pub struct JSONValidator {
scope: json_schema::scope::Scope,
id: url::Url,
}
impl JSONValidator {
pub fn new(schema: &str) -> Self {
let schema_json: Value = serde_json::from_str(schema).unwrap();
let mut scope = json_schema::Scope::new();
let id = scope.compile(schema_json, false).unwrap();
Self { id, scope }
}
pub fn validate(&self, json_str: &str) -> Result<(), ButtplugSerializerError> {
let schema = self.scope.resolve(&self.id).unwrap();
let check_value = serde_json::from_str(json_str)
.map_err(|err| ButtplugSerializerError::JsonSerializerError(format!("{:?}", err)))?;
let state = schema.validate(&check_value);
if state.is_valid() {
Ok(())
} else {
Err(ButtplugSerializerError::JsonValidatorError(format!(
"{:?}",
state
)))
}
}
}