Skip to main content

vld/combinators/
preprocess.rs

1use serde_json::Value;
2
3use crate::error::VldError;
4use crate::schema::VldSchema;
5
6/// Applies a preprocessing function to the JSON value before validation.
7///
8/// Created via [`vld::preprocess()`](crate::preprocess).
9///
10/// # Example
11/// ```
12/// use vld::prelude::*;
13///
14/// // Trim whitespace from string values before validating
15/// let schema = vld::preprocess(
16///     |v| match v.as_str() {
17///         Some(s) => serde_json::Value::String(s.trim().to_string()),
18///         None => v.clone(),
19///     },
20///     vld::string().min(1),
21/// );
22/// ```
23pub struct ZPreprocess<F, S>
24where
25    F: Fn(&Value) -> Value,
26    S: VldSchema,
27{
28    preprocessor: F,
29    schema: S,
30}
31
32impl<F, S> ZPreprocess<F, S>
33where
34    F: Fn(&Value) -> Value,
35    S: VldSchema,
36{
37    pub fn new(preprocessor: F, schema: S) -> Self {
38        Self {
39            preprocessor,
40            schema,
41        }
42    }
43
44    /// Access the inner schema (for nested OpenAPI component collection).
45    pub fn inner_schema(&self) -> &S {
46        &self.schema
47    }
48}
49
50impl<F, S> VldSchema for ZPreprocess<F, S>
51where
52    F: Fn(&Value) -> Value,
53    S: VldSchema,
54{
55    type Output = S::Output;
56
57    fn parse_value(&self, value: &Value) -> Result<S::Output, VldError> {
58        let preprocessed = (self.preprocessor)(value);
59        self.schema.parse_value(&preprocessed)
60    }
61}