Skip to main content

Module validation

Module validation 

Source
Available on crate feature validation only.
Expand description

Validating request documents before they reach your code.

JSON:API wraps a resource in a {"data":{"type","id","attributes","relationships"}} envelope. This module builds a JSON Schema for that envelope from your resource’s Schema plus a JSON Schema for its attributes, and checks request bodies against it.

ⓘ
let validator = DocumentValidator::builder(&todo_schema)
    .attributes(serde_json::json!({
        "type": "object",
        "properties": { "message": { "type": "string" } },
        "required": ["message"],
    }))
    .build()?;

let json = validator.parse(&body, &ctx)?;   // Vec<JsonApiError> on failure

The pay-off is the errors. Each failure is reported with its instance location as a JSON Pointer, which is exactly what JSON:API’s source.pointer is — so one malformed body comes back as a complete error document, pointing at every member that caused it, with no per-field checks written by hand.

§format

JSON Schema 2020-12 treats format as an annotation, so "format": "email" checks nothing by default. This crate asserts it instead: a request schema that names a format is stating a rule, and a rule that silently does nothing is worse than none. date, date-time, time, duration, email, idn-email, hostname, ipv4, ipv6, uuid, json-pointer and relative-json-pointer are checked; ValidatorBuilder::format supplies a check for anything else, and ValidatorBuilder::annotate_formats turns assertion off.

With resource!, a field typed Formatted<Email> declares and asserts the format in one place.

Using ash-domain? DocumentValidator::for_create derives the attribute schema from a ResourceSchema, so there is nothing to write.

Structs§

DocumentValidator
Validates create documents for one resource.
ValidatorBuilder
Builds a DocumentValidator for one resource.

Enums§

BuildError
Why a validator could not be built from a resource schema.