pleme_error/
field_validator.rs1use crate::ServiceError;
20
21#[derive(Debug, Default)]
23pub struct FieldValidator {
24 errors: Vec<(String, String)>,
25}
26
27impl FieldValidator {
28 pub fn new() -> Self {
30 Self { errors: Vec::new() }
31 }
32
33 pub fn add(&mut self, field: &str, message: &str) {
35 self.errors.push((field.to_string(), message.to_string()));
36 }
37
38 pub fn add_if(&mut self, condition: bool, field: &str, message: &str) {
40 if condition {
41 self.add(field, message);
42 }
43 }
44
45 pub fn is_empty(&self) -> bool {
47 self.errors.is_empty()
48 }
49
50 pub fn len(&self) -> usize {
52 self.errors.len()
53 }
54
55 pub fn errors(&self) -> &[(String, String)] {
57 &self.errors
58 }
59
60 pub fn into_service_error(self) -> ServiceError {
62 validation_errors_from_fields(self.errors)
63 }
64
65 pub fn into_errors(self) -> Vec<(String, String)> {
67 self.errors
68 }
69
70 pub fn as_static_errors(&self) -> Vec<(&str, &str)> {
72 self.errors.iter()
73 .map(|(f, m)| (f.as_str(), m.as_str()))
74 .collect()
75 }
76}
77
78pub fn validation_errors_from_fields(errors: Vec<(String, String)>) -> ServiceError {
80 let error_map: std::collections::HashMap<String, Vec<String>> = errors.into_iter()
81 .fold(std::collections::HashMap::new(), |mut acc, (field, msg)| {
82 acc.entry(field).or_insert_with(Vec::new).push(msg);
83 acc
84 });
85
86 ServiceError::ValidationErrors(error_map)
87}
88
89pub fn validation_from_fields(errors: Vec<(&str, &str)>) -> ServiceError {
91 let converted: Vec<(String, String)> = errors.into_iter()
92 .map(|(field, msg)| (field.to_string(), msg.to_string()))
93 .collect();
94 validation_errors_from_fields(converted)
95}