schemars.rs

 1use schemars::{JsonSchema, transform::transform_subschemas};
 2
 3const DEFS_PATH: &str = "#/$defs/";
 4
 5/// Replaces the JSON schema definition for some type if it is in use (in the definitions list), and
 6/// returns a reference to it.
 7///
 8/// This asserts that JsonSchema::schema_name() + "2" does not exist because this indicates that
 9/// there are multiple types that use this name, and unfortunately schemars APIs do not support
10/// resolving this ambiguity - see <https://github.com/GREsau/schemars/issues/449>
11///
12/// This takes a closure for `schema` because some settings types are not available on the remote
13/// server, and so will crash when attempting to access e.g. GlobalThemeRegistry.
14pub fn replace_subschema<T: JsonSchema>(
15    generator: &mut schemars::SchemaGenerator,
16    schema: impl Fn() -> schemars::Schema,
17) -> schemars::Schema {
18    let schema_name = T::schema_name();
19    let definitions = generator.definitions_mut();
20    assert!(!definitions.contains_key(&format!("{schema_name}2")));
21    if definitions.contains_key(schema_name.as_ref()) {
22        definitions.insert(schema_name.to_string(), schema().to_value());
23    }
24    schemars::Schema::new_ref(format!("{DEFS_PATH}{schema_name}"))
25}
26
27/// Adds a new JSON schema definition and returns a reference to it. **Panics** if the name is
28/// already in use.
29pub fn add_new_subschema(
30    generator: &mut schemars::SchemaGenerator,
31    name: &str,
32    schema: serde_json::Value,
33) -> schemars::Schema {
34    let old_definition = generator.definitions_mut().insert(name.to_string(), schema);
35    assert_eq!(old_definition, None);
36    schemars::Schema::new_ref(format!("{DEFS_PATH}{name}"))
37}
38
39/// Defaults `additionalProperties` to `true`, as if `#[schemars(deny_unknown_fields)]` was on every
40/// struct. Skips structs that have `additionalProperties` set (such as if #[serde(flatten)] is used
41/// on a map).
42#[derive(Clone)]
43pub struct DefaultDenyUnknownFields;
44
45impl schemars::transform::Transform for DefaultDenyUnknownFields {
46    fn transform(&mut self, schema: &mut schemars::Schema) {
47        if let Some(object) = schema.as_object_mut()
48            && object.contains_key("properties")
49            && !object.contains_key("additionalProperties")
50            && !object.contains_key("unevaluatedProperties")
51        {
52            object.insert("additionalProperties".to_string(), false.into());
53        }
54        transform_subschemas(self, schema);
55    }
56}