zod_rs/schema/
mod.rs

1mod array;
2mod boolean;
3mod literal;
4mod null;
5mod number;
6mod object;
7mod optional;
8mod string;
9mod tuple;
10mod union;
11
12pub use array::*;
13pub use boolean::*;
14pub use literal::*;
15pub use null::*;
16pub use number::*;
17pub use object::*;
18pub use optional::*;
19pub use string::*;
20pub use tuple::*;
21pub use union::*;
22
23use serde_json::Value;
24use std::fmt::Debug;
25use zod_rs_util::ValidateResult;
26
27pub trait Schema<T>: Debug
28where
29    T: std::fmt::Debug,
30{
31    /// Validates the value against this schema and returns the validated result.
32    fn validate(&self, value: &Value) -> ValidateResult<T>;
33
34    /// Validates and returns the result, panicking on validation failure.
35    ///
36    /// # Panics
37    /// Panics if validation fails. Use `safe_parse()` or `validate()` for non-panicking alternatives.
38    ///
39    /// # Example
40    /// ```should_panic
41    /// use zod_rs::prelude::*;
42    /// use serde_json::json;
43    ///
44    /// let schema = string().min(5);
45    /// let result = schema.parse(&json!("hi")); // panics: string too short
46    /// ```
47    fn parse(&self, value: &Value) -> T {
48        match self.validate(value) {
49            Ok(result) => result,
50            Err(errors) => panic!("Validation failed: {errors}"),
51        }
52    }
53
54    /// Validates the value and returns a Result. This is the recommended method for handling
55    /// validation in production code.
56    fn safe_parse(&self, value: &Value) -> ValidateResult<T> {
57        self.validate(value)
58    }
59
60    fn optional(self) -> OptionalSchema<Self, T>
61    where
62        Self: Sized,
63    {
64        OptionalSchema::new(self)
65    }
66
67    fn array(self) -> ArraySchema<Self, T>
68    where
69        Self: Sized,
70    {
71        ArraySchema::new(self)
72    }
73}