Skip to main content

ferrin_schema/
dialect.rs

1//! JSON Schema dialects used for generation.
2
3use schemars::JsonSchema;
4use schemars::generate::SchemaSettings;
5use serde_json::Value;
6
7/// JSON Schema draft used when generating schemas from Rust types.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
9#[non_exhaustive]
10pub enum SchemaDialect {
11    /// Draft-07: the dialect providers and adapter transforms are built on.
12    #[default]
13    Draft07,
14    /// Draft 2020-12.
15    Draft2020_12,
16}
17
18impl SchemaDialect {
19    /// Returns the `schemars` settings for this dialect.
20    #[must_use]
21    pub fn settings(self) -> SchemaSettings {
22        match self {
23            Self::Draft07 => SchemaSettings::draft07(),
24            Self::Draft2020_12 => SchemaSettings::draft2020_12(),
25        }
26    }
27
28    /// Generates the root schema of `T` as a JSON value.
29    #[must_use]
30    pub fn generate<T: JsonSchema>(self) -> Value {
31        self.settings()
32            .into_generator()
33            .into_root_schema_for::<T>()
34            .to_value()
35    }
36
37    /// Returns the `$schema` URI of this dialect.
38    #[must_use]
39    pub fn meta_schema(self) -> &'static str {
40        match self {
41            Self::Draft07 => "http://json-schema.org/draft-07/schema#",
42            Self::Draft2020_12 => "https://json-schema.org/draft/2020-12/schema",
43        }
44    }
45}