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

source

pub fn compile<'a>( &self, schema: &'a Value, ) -> Result<JSONSchema, ValidationError<'a>>

Compile schema into JSONSchema using the currently defined options.

source

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);
source

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 return true 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);
source

pub fn with_resolver( &mut self, resolver: impl SchemaResolver + 'static, ) -> &mut Self

Use a custom resolver for resolving external schema references.

source

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");
source

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 return true 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 a jsonschema crate supported error (obtained via ? or From::from APIs)
    • Ok(None): if the input string is not valid according to the content encoding
    • Ok(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);
source

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");
source

pub fn with_meta_schemas(&mut self) -> &mut Self

👎Deprecated since 0.19.0: Meta schemas are now included by default

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.

source

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.

source

pub fn with_format<N, F>(&mut self, name: N, format: F) -> &mut Self
where N: Into<String>, F: Fn(&str) -> bool + Send + Sync + 'static,

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.

source

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.

source

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.

source

pub fn with_keyword<N, F>(&mut self, name: N, factory: F) -> &mut Self
where N: Into<String>, F: for<'a> Fn(&'a Map<String, Value>, &'a Value, JSONPointer) -> Result<Box<dyn Keyword>, ValidationError<'a>> + Send + Sync + 'static,

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

source§

fn clone(&self) -> CompilationOptions

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for CompilationOptions

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for CompilationOptions

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more