diff options
Diffstat (limited to 'src/validator.rs')
| -rw-r--r-- | src/validator.rs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/validator.rs b/src/validator.rs new file mode 100644 index 0000000..1fa52bc --- /dev/null +++ b/src/validator.rs @@ -0,0 +1,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(); + } +} |