jsonschema_valid/
config.rs

1use 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
11/// A structure to hold configuration for a validation run.
12pub struct Config<'a> {
13    schema: &'a Value,
14    resolver: Resolver<'a>,
15    pub(crate) draft: schemas::Draft,
16}
17
18impl<'a> Config<'a> {
19    /// Get the validator object for the draft in use.
20    pub fn get_validator<'v>(&self, key: &'v str) -> Option<Validator<'v>> {
21        self.draft.get_validator(key)
22    }
23
24    /// Get the string format checker for the draft in use.
25    pub fn get_format_checker(&self, key: &str) -> Option<FormatChecker> {
26        self.draft.get_format_checker(key)
27    }
28
29    /// Get the draft number in use.
30    pub fn get_draft_number(&self) -> u8 {
31        self.draft.get_draft_number()
32    }
33
34    /// Get the metaschema associated with the draft in use.
35    pub fn get_metaschema(&self) -> &Value {
36        self.draft.get_schema()
37    }
38
39    /// Get the resolver for the parsing context.
40    pub fn get_resolver(&self) -> &Resolver<'a> {
41        &self.resolver
42    }
43
44    /// Get the schema currently being checked against.
45    pub fn get_schema(&self) -> &Value {
46        self.schema
47    }
48
49    /// Create a new Config object from a given schema.
50    ///
51    /// Will use the Draft of JSON schema specified by `draft`. If `draft` is
52    /// `None`, it will be automatically determined from the `$schema` entry in
53    /// the given `schema`. If no `$schema` entry is present Draft 7 will be used
54    /// by default.
55    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    /// Validate the given JSON instance against the schema.
70    pub fn validate(&'a self, instance: &'a Value) -> Result<(), ErrorIterator<'a>> {
71        crate::validate(self, instance)
72    }
73
74    /// Validate the schema in this Config object against the metaschema.
75    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}