Skip to main content

vld/collections/
record.rs

1use serde_json::Value;
2use std::collections::{BTreeMap, HashMap};
3use std::marker::PhantomData;
4
5use crate::error::{IssueCode, PathSegment, SizeOrigin, VldError};
6use crate::schema::VldSchema;
7
8/// How a record turns a JSON object key into an output key: [`AnyKey`]
9/// (plain `String`) or [`KeySchema`] (validated by a schema).
10pub trait RecordKey {
11    /// Output key type.
12    type Output;
13    /// Parse one object key.
14    fn parse_key(&self, key: &str) -> Result<Self::Output, VldError>;
15}
16
17/// Record keys taken as is (`String`, no validation). Default of [`ZRecord`].
18#[derive(Clone, Copy, Default)]
19pub struct AnyKey;
20
21impl RecordKey for AnyKey {
22    type Output = String;
23
24    fn parse_key(&self, key: &str) -> Result<String, VldError> {
25        Ok(key.to_owned())
26    }
27}
28
29/// Record keys validated by a schema, which receives each key as a JSON
30/// string. Created by [`vld::record_with_keys()`](crate::record_with_keys).
31#[derive(Clone)]
32pub struct KeySchema<K>(pub K);
33
34impl<K: VldSchema> RecordKey for KeySchema<K> {
35    type Output = K::Output;
36
37    fn parse_key(&self, key: &str) -> Result<K::Output, VldError> {
38        self.0.parse_value(&Value::String(key.to_owned()))
39    }
40}
41
42/// Schema for validating JSON objects as key-value records.
43/// Created via [`vld::record()`](crate::record) (`HashMap<String, V>`) or
44/// [`vld::record_with_keys()`](crate::record_with_keys) (`HashMap<K, V>`);
45/// [`ordered()`](Self::ordered) switches the output to a `BTreeMap`.
46///
47/// Values are validated against the value schema; key and value issues are
48/// reported at the key's path. If two keys parse to the same output key, the
49/// later one wins.
50///
51/// # Example
52/// ```
53/// use vld::prelude::*;
54///
55/// let schema = vld::record(vld::number().int().positive());
56/// let result = schema.parse(r#"{"a": 1, "b": 2}"#).unwrap();
57/// assert_eq!(result.get("a"), Some(&1));
58///
59/// let ordered = vld::record(vld::boolean()).ordered().parse(r#"{"b": true, "a": false}"#).unwrap();
60/// assert_eq!(ordered.keys().collect::<Vec<_>>(), ["a", "b"]);
61/// ```
62pub struct ZRecord<V: VldSchema, K = AnyKey, M = HashMap<String, <V as VldSchema>::Output>> {
63    key_schema: K,
64    value_schema: V,
65    min_keys: Option<usize>,
66    max_keys: Option<usize>,
67    _map: PhantomData<fn() -> M>,
68}
69
70/// Record with `BTreeMap` output (sorted keys); see [`ZRecord::ordered`].
71pub type ZOrderedRecord<V, K = AnyKey> =
72    ZRecord<V, K, BTreeMap<<K as RecordKey>::Output, <V as VldSchema>::Output>>;
73
74impl<V: VldSchema> ZRecord<V> {
75    /// Create the schema (the same as its `vld::` constructor function).
76    pub fn new(value_schema: V) -> Self {
77        Self::with_keys(AnyKey, value_schema)
78    }
79}
80
81impl<V: VldSchema, K, M> ZRecord<V, K, M> {
82    pub(crate) fn with_keys(key_schema: K, value_schema: V) -> Self {
83        Self {
84            key_schema,
85            value_schema,
86            min_keys: None,
87            max_keys: None,
88            _map: PhantomData,
89        }
90    }
91
92    /// Minimum number of keys.
93    pub fn min_keys(mut self, n: usize) -> Self {
94        self.min_keys = Some(n);
95        self
96    }
97
98    /// Maximum number of keys.
99    pub fn max_keys(mut self, n: usize) -> Self {
100        self.max_keys = Some(n);
101        self
102    }
103
104    /// Produce a `BTreeMap` (sorted by key) instead of a `HashMap`.
105    pub fn ordered(self) -> ZOrderedRecord<V, K>
106    where
107        K: RecordKey,
108        K::Output: Ord,
109    {
110        ZRecord {
111            key_schema: self.key_schema,
112            value_schema: self.value_schema,
113            min_keys: self.min_keys,
114            max_keys: self.max_keys,
115            _map: PhantomData,
116        }
117    }
118}
119
120impl<V, K, M> VldSchema for ZRecord<V, K, M>
121where
122    V: VldSchema,
123    K: RecordKey,
124    M: Default + Extend<(K::Output, V::Output)>,
125{
126    type Output = M;
127
128    fn parse_value(&self, value: &Value) -> Result<M, VldError> {
129        let obj = value
130            .as_object()
131            .ok_or_else(|| crate::primitives::type_error(&None, "object", value))?;
132
133        let mut errors = VldError::new();
134        // An inner `Err` may carry no issues: track failure, not issue count.
135        let mut failed = false;
136
137        if let Some(min) = self.min_keys
138            && obj.len() < min
139        {
140            errors.push_code(IssueCode::TooSmall {
141                origin: SizeOrigin::Record,
142                minimum: min.into(),
143                inclusive: true,
144            });
145        }
146
147        if let Some(max) = self.max_keys
148            && obj.len() > max
149        {
150            errors.push_code(IssueCode::TooBig {
151                origin: SizeOrigin::Record,
152                maximum: max.into(),
153                inclusive: true,
154            });
155        }
156
157        let mut result = M::default();
158
159        for (key, val) in obj {
160            let k = self.key_schema.parse_key(key);
161            let v = self.value_schema.parse_value(val);
162            match (k, v) {
163                (Ok(k), Ok(v)) => result.extend(std::iter::once((k, v))),
164                (k, v) => {
165                    failed = true;
166                    for e in [k.err(), v.err()].into_iter().flatten() {
167                        errors = errors.merge(e.with_prefix(PathSegment::Field(key.clone())));
168                    }
169                }
170            }
171        }
172
173        if errors.is_empty() && !failed {
174            Ok(result)
175        } else {
176            Err(errors)
177        }
178    }
179}
180
181#[cfg(feature = "openapi")]
182impl crate::openapi::JsonSchema for AnyKey {
183    fn json_schema(&self) -> Value {
184        serde_json::json!({})
185    }
186}
187
188#[cfg(feature = "openapi")]
189impl<K: crate::openapi::JsonSchema> crate::openapi::JsonSchema for KeySchema<K> {
190    fn json_schema(&self) -> Value {
191        self.0.json_schema()
192    }
193}
194
195/// `{"type": "object", "additionalProperties": <value>}`; a key schema adds
196/// `propertyNames`.
197#[cfg(feature = "openapi")]
198impl<V, K, M> crate::openapi::JsonSchema for ZRecord<V, K, M>
199where
200    V: VldSchema + crate::openapi::JsonSchema,
201    K: crate::openapi::JsonSchema,
202{
203    fn json_schema(&self) -> Value {
204        let mut schema = serde_json::json!({
205            "type": "object",
206            "additionalProperties": self.value_schema.json_schema(),
207        });
208        let keys = self.key_schema.json_schema();
209        if keys.as_object().is_some_and(|o| !o.is_empty()) {
210            schema["propertyNames"] = keys;
211        }
212        crate::primitives::length_schema(
213            &mut schema,
214            ("minProperties", "maxProperties"),
215            self.min_keys,
216            self.max_keys,
217        );
218        schema
219    }
220}
221
222#[cfg(feature = "openapi")]
223impl<V, K, M> crate::openapi::CollectNestedSchemas for ZRecord<V, K, M>
224where
225    V: VldSchema + crate::openapi::CollectNestedSchemas,
226{
227    fn collect_nested_schemas(&self, out: &mut Vec<crate::schema::NestedSchemaEntry>) {
228        self.value_schema.collect_nested_schemas(out);
229    }
230}