jsonschema_valid/
config.rs1use serde_json::Value;
2
3use crate::context::Context;
4use crate::error::{ErrorIterator, ValidationError};
5use crate::format::FormatChecker;
6use crate::resolver::Resolver;
7use crate::schemas;
8use crate::validators;
9use crate::validators::Validator;
10
11pub struct Config<'a> {
13 schema: &'a Value,
14 resolver: Resolver<'a>,
15 pub(crate) draft: schemas::Draft,
16}
17
18impl<'a> Config<'a> {
19 pub fn get_validator<'v>(&self, key: &'v str) -> Option<Validator<'v>> {
21 self.draft.get_validator(key)
22 }
23
24 pub fn get_format_checker(&self, key: &str) -> Option<FormatChecker> {
26 self.draft.get_format_checker(key)
27 }
28
29 pub fn get_draft_number(&self) -> u8 {
31 self.draft.get_draft_number()
32 }
33
34 pub fn get_metaschema(&self) -> &Value {
36 self.draft.get_schema()
37 }
38
39 pub fn get_resolver(&self) -> &Resolver<'a> {
41 &self.resolver
42 }
43
44 pub fn get_schema(&self) -> &Value {
46 self.schema
47 }
48
49 pub fn from_schema(
56 schema: &'a Value,
57 draft: Option<schemas::Draft>,
58 ) -> Result<Config<'a>, ValidationError> {
59 let draft = draft.unwrap_or_else(|| {
60 schemas::draft_from_schema(schema).unwrap_or(schemas::Draft::Draft7)
61 });
62 Ok(Config {
63 schema,
64 resolver: Resolver::from_schema(draft, schema)?,
65 draft,
66 })
67 }
68
69 pub fn validate(&'a self, instance: &'a Value) -> Result<(), ErrorIterator<'a>> {
71 crate::validate(self, instance)
72 }
73
74 pub fn validate_schema(&'a self) -> Result<(), ErrorIterator<'a>> {
76 let mut errors = validators::descend(
77 self,
78 self.get_schema(),
79 self.get_metaschema(),
80 None,
81 Context::new_from(self.get_metaschema()),
82 )
83 .peekable();
84
85 if errors.peek().is_none() {
86 Ok(())
87 } else {
88 Err(Box::new(errors))
89 }
90 }
91}