json_utils/schema/
schema_compiled.rs

1
2lazy_static! {
3    static ref ROOT_URL: url::Url = {
4        use std::str::FromStr;
5        url::Url::from_str("json-schema://root").expect("failed to create schema root-url")
6    };
7}
8
9use valico::json_schema::Scope;
10
11use crate::json::JsValue;
12
13#[derive(Debug, Fail)]
14#[fail(display = "ValidationError: {:?}", _0)]
15pub struct ValidationError(pub JsValue);
16
17#[derive(Debug)]
18pub struct SchemaCompiled(pub Scope);
19
20impl SchemaCompiled {
21    pub fn root_url() -> &'static url::Url {
22        &*ROOT_URL
23    }
24    pub fn validate(&self, value: &JsValue) -> Result<(), ValidationError> {
25        let schema = self.0.resolve(Self::root_url()).expect("Failed to resolve schema root-url");
26        let validation_state = schema.validate(value);
27        if validation_state.is_valid() {
28            Ok(())
29        } else {
30            let validation_error_json = serde_json::to_value(validation_state).unwrap();
31            let validation_error = ValidationError(validation_error_json);
32            Err(validation_error)
33        }
34    }
35}