1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use crate::core::message::serializer::ButtplugSerializerError;
use jsonschema::JSONSchema;
pub struct JSONValidator {
schema: JSONSchema,
}
impl JSONValidator {
pub fn new(schema: &str) -> Self {
let schema_json: serde_json::Value =
serde_json::from_str(schema).expect("Built in schema better be valid");
let schema = JSONSchema::compile(&schema_json).expect("Built in schema better be valid");
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: {} - Error: {:?}",
json_str, err
))
})?;
self.schema.validate(&check_value).map_err(|err| {
let err_vec: Vec<jsonschema::ValidationError> = err.collect();
ButtplugSerializerError::JsonSerializerError(format!(
"Error during JSON Schema Validation: {:?}",
err_vec
))
})
}
}