Skip to main content

vld/modifiers/
nullish.rs

1use serde_json::Value;
2
3use crate::error::VldError;
4use crate::schema::VldSchema;
5
6/// Wraps a schema to make it both optional and nullable (nullish).
7///
8/// Equivalent to `.optional()` + `.nullable()` in Zod.
9/// If the value is `null` or missing, returns `Ok(None)`.
10pub struct ZNullish<T: VldSchema> {
11    inner: T,
12}
13
14impl<T: VldSchema> ZNullish<T> {
15    pub fn new(inner: T) -> Self {
16        Self { inner }
17    }
18
19    /// Access the inner schema (for JSON Schema generation).
20    pub fn inner_schema(&self) -> &T {
21        &self.inner
22    }
23}
24
25impl<T: VldSchema> VldSchema for ZNullish<T> {
26    type Output = Option<T::Output>;
27
28    fn parse_value(&self, value: &Value) -> Result<Option<T::Output>, VldError> {
29        if value.is_null() {
30            return Ok(None);
31        }
32        self.inner.parse_value(value).map(Some)
33    }
34}