Schemas
Requires the
schemaCargo feature, which is not enabled by default.
The other feature of Schematic is the ability to model schemas for Rust types using the
Schematic trait and associated macro. Schemas are useful for:
- Generating code, documentation, and other formats.
- Ensuring data integrity across systems.
- Standardizing interoperability and enforcing contracts.
Usage
Define a struct, enum, or type and derive the Schematic trait. Our macro will attempt
to convert all fields, variants, values, and generics into a schema representation using
SchemaType.
#![allow(unused)] fn main() { use schematic::Schematic; #[derive(Schematic)] enum UserStatus { Active, Inactive, } #[derive(Schematic)] struct User { pub name: String; pub age: usize; pub status: UserStatus; } }
Once a type has a schema associated with it, it can be fed into the generator.
Custom implementation
Our derive macro will always implement schemas using the default state of Schema,
SchemaType, and associated types. If you want these types to use
custom settings, you can implement the Schematic trait and
Schematic::build_schema()
method manually.
The
Schematic::schema_name()
method is optional, but is encouraged for non-primitive types. It will associate references between
types, and avoid circular references.
#![allow(unused)] fn main() { use schematic::{Schematic, Schema, SchemaBuilder, SchemaType, schema::*}; #[derive(Schematic)] enum UserStatus { Active, Inactive, } struct User { pub name: String; pub age: usize; pub status: UserStatus; } impl Schematic for User { fn schema_name() -> Option<String> { Some("User".into()) } fn build_schema(mut schema: SchemaBuilder) -> Schema { schema.structure(StructType::new([ ("name".into(), schema.nest().string(StringType { min_length: Some(1), ..StringType::default() })), ("age".into(), schema.nest().integer(IntegerType::new_kind(IntegerKind::Usize))), ("status".into(), schema.infer::<UserStatus>()), ])) } } }
Learn more about our supported types.
Cargo features
The following Cargo features are available:
Renderers
Learn more about renderers.
renderer_json_schema- Enables JSON schema generation.renderer_template- Enables config template generation.renderer_typescript- Enables TypeScript types generation.
External types
Learn more about external types.
type_chrono- Implements schematic for thechronocrate.type_indexmap- Implements schematic for theindexmapcrate.type_regex- Implements schematic for theregexcrate.type_relative_path- Implements schematic for therelative-pathcrate.type_rust_decimal- Implements schematic for therust_decimalcrate.type_semver- Implements schematic for thesemvercrate.type_url- Implements schematic for theurlcrate.type_uuid- Implements schematic for theuuidcrate.