Struct jsonschema::CompilationOptions
source · pub struct CompilationOptions { /* private fields */ }
Expand description
Full configuration to guide the JSONSchema
compilation.
Using a CompilationOptions
instance you can configure the supported draft,
content media types and more (check the exposed methods)
Implementations§
source§impl CompilationOptions
impl CompilationOptions
sourcepub fn compile<'a>(
&self,
schema: &'a Value,
) -> Result<JSONSchema, ValidationError<'a>>
pub fn compile<'a>( &self, schema: &'a Value, ) -> Result<JSONSchema, ValidationError<'a>>
Compile schema
into JSONSchema
using the currently defined options.
sourcepub fn with_draft(&mut self, draft: Draft) -> &mut Self
pub fn with_draft(&mut self, draft: Draft) -> &mut Self
Ensure that the schema is going to be compiled using the defined Draft.
options.with_draft(Draft::Draft4);
sourcepub fn with_content_media_type(
&mut self,
media_type: &'static str,
media_type_check: fn(_: &str) -> bool,
) -> &mut Self
pub fn with_content_media_type( &mut self, media_type: &'static str, media_type_check: fn(_: &str) -> bool, ) -> &mut Self
Ensure that compiled schema is going to support the provided content media type.
Arguments:
media_type
: Name of the content media type to support (ie. “application/json”)media_type_check
: Method checking the validity of the input string according to the media type. The method should returntrue
if the input is valid,false
otherwise.
Example:
fn check_custom_media_type(instance_string: &str) -> bool {
// In reality the check might be a bit more different ;)
instance_string != "not good"
}
// Add support for application/jsonschema-test
options.with_content_media_type("application/jsonschema-test", check_custom_media_type);
sourcepub fn with_resolver(
&mut self,
resolver: impl SchemaResolver + 'static,
) -> &mut Self
pub fn with_resolver( &mut self, resolver: impl SchemaResolver + 'static, ) -> &mut Self
Use a custom resolver for resolving external schema references.
sourcepub fn without_content_media_type_support(
&mut self,
media_type: &'static str,
) -> &mut Self
pub fn without_content_media_type_support( &mut self, media_type: &'static str, ) -> &mut Self
Ensure that compiled schema is not supporting the provided content media type.
// Disable support for application/json (which is supported by jsonschema crate)
options.without_content_media_type_support("application/json");
sourcepub fn with_content_encoding(
&mut self,
content_encoding: &'static str,
content_encoding_check: fn(_: &str) -> bool,
content_encoding_converter: fn(_: &str) -> Result<Option<String>, ValidationError<'static>>,
) -> &mut Self
pub fn with_content_encoding( &mut self, content_encoding: &'static str, content_encoding_check: fn(_: &str) -> bool, content_encoding_converter: fn(_: &str) -> Result<Option<String>, ValidationError<'static>>, ) -> &mut Self
Ensure that compiled schema is going to support the provided content encoding.
Arguments:
content_encoding
: Name of the content encoding to support (ie. “base64”)content_encoding_check
: Method checking the validity of the input string according to content encoding. The method should returntrue
if the input is valid,false
otherwise.content_encoding_converter
: Method converting the input string into a string representation (generally output of the decoding of the content encoding). The method should return:Err(ValidationError instance)
: in case of ajsonschema
crate supported error (obtained via?
orFrom::from
APIs)Ok(None)
: if the input string is not valid according to the content encodingOk(Some(content))
: if the input string is valid according to the content encoding,content
will contain the string representation of the decoded input
Example:
// The instance_string contains a number (representing the length of the string)
// a space and then the string (whose length should match the expectation).
// Example: "3 The" or "4 123"
fn check_custom_encoding(instance_string: &str) -> bool {
if let Some(first_space_index) = instance_string.find(' ') {
if let Ok(value) = instance_string[..first_space_index].parse::<u64>() {
return instance_string[first_space_index + 1..].chars().count() == value as usize;
}
}
false
}
fn converter_custom_encoding(instance_string: &str) -> Result<Option<String>, ValidationError<'static>> {
if let Some(first_space_index) = instance_string.find(' ') {
if let Ok(value) = instance_string[..first_space_index].parse::<u64>() {
if instance_string[first_space_index + 1..].chars().count() == value as usize {
return Ok(Some(instance_string[first_space_index + 1..].to_string()));
}
}
}
Ok(None)
}
// Add support for prefix-length-string
options.with_content_encoding("prefix-length-string", check_custom_encoding, converter_custom_encoding);
sourcepub fn without_content_encoding_support(
&mut self,
content_encoding: &'static str,
) -> &mut Self
pub fn without_content_encoding_support( &mut self, content_encoding: &'static str, ) -> &mut Self
Ensure that compiled schema is not supporting the provided content encoding.
// Disable support for base64 (which is supported by jsonschema crate)
options.without_content_encoding_support("base64");
sourcepub fn with_meta_schemas(&mut self) -> &mut Self
👎Deprecated since 0.19.0: Meta schemas are now included by default
pub fn with_meta_schemas(&mut self) -> &mut Self
Add meta schemas for supported JSON Schema drafts. It is helpful if your schema has references to JSON Schema meta-schemas:
{
"schema": {
"multipleOf": {
"$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf"
},
"maximum": {
"$ref": "http://json-schema.org/draft-04/schema#/properties/maximum"
}
}
}
The example above is taken from the Swagger 2.0 JSON schema.
sourcepub fn with_document(&mut self, id: String, document: Value) -> &mut Self
pub fn with_document(&mut self, id: String, document: Value) -> &mut Self
Add a new document to the store. It works as a cache to avoid making additional network
calls to remote schemas via the $ref
keyword.
sourcepub fn with_format<N, F>(&mut self, name: N, format: F) -> &mut Self
pub fn with_format<N, F>(&mut self, name: N, format: F) -> &mut Self
Register a custom “format” validator.
§Example
fn my_format(s: &str) -> bool {
// Your awesome format check!
s.ends_with("42!")
}
let schema = json!({"type": "string", "format": "custom"});
let compiled = JSONSchema::options()
.with_format("custom", my_format)
.compile(&schema)
.expect("Valid schema");
// Invalid string
assert!(!compiled.is_valid(&json!("foo")));
// Valid string
assert!(compiled.is_valid(&json!("foo42!")));
The format check function should receive &str
and return bool
.
sourcepub fn should_validate_formats(&mut self, validate_formats: bool) -> &mut Self
pub fn should_validate_formats(&mut self, validate_formats: bool) -> &mut Self
Force enable or disable format validation. The default behavior is dependent on draft version, but the default behavior can be overridden to validate or not regardless of draft.
sourcepub fn should_ignore_unknown_formats(
&mut self,
should_ignore_unknown_formats: bool,
) -> &mut Self
pub fn should_ignore_unknown_formats( &mut self, should_ignore_unknown_formats: bool, ) -> &mut Self
Set the false
if unrecognized formats should be reported as a validation error.
By default unknown formats are silently ignored.
sourcepub fn with_keyword<N, F>(&mut self, name: N, factory: F) -> &mut Self
pub fn with_keyword<N, F>(&mut self, name: N, factory: F) -> &mut Self
Register a custom keyword definition.
§Example
struct MyCustomValidator;
impl Keyword for MyCustomValidator {
fn validate<'instance>(
&self,
instance: &'instance Value,
instance_path: &JsonPointerNode,
) -> ErrorIterator<'instance> {
// ... validate instance ...
if !instance.is_object() {
let error = ValidationError::custom(
JSONPointer::default(),
instance_path.into(),
instance,
"Boom!",
);
Box::new(once(error))
} else {
Box::new(None.into_iter())
}
}
fn is_valid(&self, instance: &Value) -> bool {
// ... determine if instance is valid ...
true
}
}
// You can create a factory function, or use a closure to create new validator instances.
fn custom_validator_factory<'a>(
parent: &'a Map<String, Value>,
value: &'a Value,
path: JSONPointer,
) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
Ok(Box::new(MyCustomValidator))
}
assert!(JSONSchema::options()
.with_keyword("my-type", custom_validator_factory)
.with_keyword("my-type-with-closure", |_, _, _| Ok(Box::new(MyCustomValidator)))
.compile(&json!({ "my-type": "my-schema"}))
.expect("A valid schema")
.is_valid(&json!({ "a": "b"})));
Trait Implementations§
source§impl Clone for CompilationOptions
impl Clone for CompilationOptions
source§fn clone(&self) -> CompilationOptions
fn clone(&self) -> CompilationOptions
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl Debug for CompilationOptions
impl Debug for CompilationOptions
Auto Trait Implementations§
impl Freeze for CompilationOptions
impl !RefUnwindSafe for CompilationOptions
impl Send for CompilationOptions
impl Sync for CompilationOptions
impl Unpin for CompilationOptions
impl !UnwindSafe for CompilationOptions
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)