summaryrefslogtreecommitdiff
path: root/src/validator.rs
blob: 1fa52bc1d2f117be37d702ea3b017c6c2f5ba6d0 (plain)
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
extern crate serde;
extern crate serde_json;
extern crate valico;

use std::fs::File;
use std::io::BufReader;
use std::io::Read;

use serde_json::from_str;
use valico::json_schema;

pub struct Validator {
    schema_content: String
}

impl Validator {
    pub fn from_file(schema_path: &'static str) -> Result<Validator, String> {
        let file = match File::open(schema_path) {
            Ok(file) => file,
            Err(_) => return Err(String::from("Could not open file"))
        };
        let mut buf_reader = BufReader::new(file);
        let mut content = String::new();
        match buf_reader.read_to_string(&mut content) {
            Ok(_) => (),
            Err(_) => return Err(String::from("Could not read from file"))
        };
        return Validator::from_string(content);
    }
    
    pub fn from_string(schema: String) -> Result<Validator, String> {
        let s = match from_str(&schema) {
            Ok(schema) => schema,
            Err(_) => return Err(String::from("Could not parse schema"))
        };
        let mut scope = json_schema::Scope::new();
        match scope.compile_and_return(s, true) {
            Ok(_) => (),
            Err(_) => return Err(String::from("Could not compile schema"))
        };
        return Ok(Validator { schema_content: schema });
    }

    pub fn check(&self, content: &str) -> bool {
        let obj = from_str(content).unwrap();
        let mut scope = json_schema::Scope::new();
        let schema = from_str(&self.schema_content).unwrap();
        let schema = scope.compile_and_return(schema, true).ok().unwrap();
        return schema.validate(&obj).is_valid();
    }
}