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 { 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 { 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(); } }