yaiko_core/
schema_validation.rs1use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use std::collections::BTreeMap;
6
7#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
8pub struct FieldError {
9 pub field: String,
10 pub code: String,
11 pub message: String,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15pub struct ValidationReport {
16 pub valid: bool,
17 pub errors: Vec<FieldError>,
18}
19
20impl ValidationReport {
21 pub fn ok() -> Self {
22 Self {
23 valid: true,
24 errors: Vec::new(),
25 }
26 }
27 pub fn from_errors(errors: Vec<FieldError>) -> Self {
28 Self {
29 valid: errors.is_empty(),
30 errors,
31 }
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum SchemaRule {
37 Required,
38 StringMin(usize),
39 StringMax(usize),
40 Email,
41 Integer,
42}
43
44#[derive(Debug, Clone, Default)]
45pub struct SchemaValidator {
46 rules: BTreeMap<String, Vec<SchemaRule>>,
47}
48
49impl SchemaValidator {
50 pub fn new() -> Self {
51 Self::default()
52 }
53 pub fn rule(mut self, field: impl Into<String>, rule: SchemaRule) -> Self {
54 self.rules.entry(field.into()).or_default().push(rule);
55 self
56 }
57 pub fn required(self, field: impl Into<String>) -> Self {
58 self.rule(field, SchemaRule::Required)
59 }
60 pub fn string_min(self, field: impl Into<String>, length: usize) -> Self {
61 self.rule(field, SchemaRule::StringMin(length))
62 }
63 pub fn string_max(self, field: impl Into<String>, length: usize) -> Self {
64 self.rule(field, SchemaRule::StringMax(length))
65 }
66 pub fn email(self, field: impl Into<String>) -> Self {
67 self.rule(field, SchemaRule::Email)
68 }
69 pub fn integer(self, field: impl Into<String>) -> Self {
70 self.rule(field, SchemaRule::Integer)
71 }
72
73 pub fn validate(&self, input: &Value) -> ValidationReport {
74 let mut errors = Vec::new();
75 for (field, rules) in &self.rules {
76 let value = field_value(input, field);
77 for rule in rules {
78 if let Some(error) = validate_rule(field, value, rule) {
79 errors.push(error);
80 }
81 }
82 }
83 ValidationReport::from_errors(errors)
84 }
85}
86
87fn field_value<'a>(input: &'a Value, path: &str) -> Option<&'a Value> {
88 let mut current = input;
89 for part in path.split('.') {
90 current = current.get(part)?;
91 }
92 Some(current)
93}
94
95fn validate_rule(field: &str, value: Option<&Value>, rule: &SchemaRule) -> Option<FieldError> {
96 let missing = value.is_none() || value.is_some_and(Value::is_null);
97 let error = |code: &str, message: String| FieldError {
98 field: field.to_string(),
99 code: code.to_string(),
100 message,
101 };
102 match rule {
103 SchemaRule::Required if missing => Some(error("required", "Field is required".into())),
104 SchemaRule::StringMin(min)
105 if value
106 .and_then(Value::as_str)
107 .is_some_and(|text| text.chars().count() < *min) =>
108 {
109 Some(error(
110 "min_length",
111 format!("Must be at least {min} characters"),
112 ))
113 }
114 SchemaRule::StringMax(max)
115 if value
116 .and_then(Value::as_str)
117 .is_some_and(|text| text.chars().count() > *max) =>
118 {
119 Some(error(
120 "max_length",
121 format!("Must be no more than {max} characters"),
122 ))
123 }
124 SchemaRule::Email
125 if value
126 .and_then(Value::as_str)
127 .is_some_and(|text| !text.contains('@') || !text.contains('.')) =>
128 {
129 Some(error("email", "Must be a valid email address".into()))
130 }
131 SchemaRule::Integer if value.is_some_and(|value| !value.is_i64() && !value.is_u64()) => {
132 Some(error("integer", "Must be an integer".into()))
133 }
134 _ => None,
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141 use serde_json::json;
142
143 #[test]
144 fn validates_nested_fields_and_collects_structured_errors() {
145 let validator = SchemaValidator::new()
146 .required("user.name")
147 .email("user.email")
148 .integer("age");
149 let report = validator.validate(&json!({"user": {"email": "invalid"}, "age": "old"}));
150 assert!(!report.valid);
151 assert!(report
152 .errors
153 .iter()
154 .any(|error| error.field == "user.name" && error.code == "required"));
155 assert!(report
156 .errors
157 .iter()
158 .any(|error| error.field == "user.email" && error.code == "email"));
159 assert!(report
160 .errors
161 .iter()
162 .any(|error| error.field == "age" && error.code == "integer"));
163 }
164
165 #[test]
166 fn accepts_valid_values_and_enforces_string_bounds() {
167 let validator = SchemaValidator::new()
168 .required("name")
169 .string_min("name", 2)
170 .string_max("name", 5);
171 assert!(validator.validate(&json!({"name": "Ada"})).valid);
172 assert_eq!(
173 validator.validate(&json!({"name": "A"})).errors[0].code,
174 "min_length"
175 );
176 }
177
178 #[test]
179 fn serializes_validation_report_for_http_responses() {
180 let report = SchemaValidator::new()
181 .required("email")
182 .validate(&json!({}));
183 let json = serde_json::to_value(&report).unwrap();
184 assert_eq!(json["valid"], false);
185 assert_eq!(json["errors"][0]["field"], "email");
186 }
187}