use crate::message::serializer::ButtplugSerializerError;
use jsonschema::Validator;
pub struct JSONValidator {
schema: Validator,
}
impl JSONValidator {
pub fn new(schema: &str) -> Self {
let schema_json: serde_json::Value =
serde_json::from_str(schema).expect("schema must be valid JSON (validated by build.rs)");
let schema = Validator::new(&schema_json)
.expect("schema must be valid JSON Schema (validated by build.rs)");
Self { schema }
}
pub fn validate(&self, json_str: &str) -> Result<(), ButtplugSerializerError> {
let check_value = serde_json::from_str(json_str).map_err(|err| {
ButtplugSerializerError::JsonSerializerError(format!("Message: {json_str} - Error: {err:?}"))
})?;
self.schema.validate(&check_value).map_err(|err| {
ButtplugSerializerError::JsonSerializerError(format!(
"Error during JSON Schema Validation: {err:?}"
))
})
}
}