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    /// Create the schema (the same as its `vld::` constructor function).
38    pub fn new(preprocessor: F, schema: S) -> Self {
39        Self {
40            preprocessor,
41            schema,
42        }
43    }
44
45    /// Access the inner schema (for nested OpenAPI component collection).
46    pub fn inner_schema(&self) -> &S {
47        &self.schema
48    }
49}
50
51impl<F, S> VldSchema for ZPreprocess<F, S>
52where
53    F: Fn(&Value) -> Value,
54    S: VldSchema,
55{
56    type Output = S::Output;
57
58    fn parse_value(&self, value: &Value) -> Result<S::Output, VldError> {
59        let preprocessed = (self.preprocessor)(value);
60        self.schema.parse_value(&preprocessed)
61    }
62
63    fn output_json(&self, o: &Self::Output) -> Option<Value> {
64        self.schema.output_json(o)
65    }
66}