use crate::ServiceError;
#[derive(Debug, Default)]
pub struct FieldValidator {
errors: Vec<(String, String)>,
}
impl FieldValidator {
pub fn new() -> Self {
Self { errors: Vec::new() }
}
pub fn add(&mut self, field: &str, message: &str) {
self.errors.push((field.to_string(), message.to_string()));
}
pub fn add_if(&mut self, condition: bool, field: &str, message: &str) {
if condition {
self.add(field, message);
}
}
pub fn is_empty(&self) -> bool {
self.errors.is_empty()
}
pub fn len(&self) -> usize {
self.errors.len()
}
pub fn errors(&self) -> &[(String, String)] {
&self.errors
}
pub fn into_service_error(self) -> ServiceError {
validation_errors_from_fields(self.errors)
}
pub fn into_errors(self) -> Vec<(String, String)> {
self.errors
}
pub fn as_static_errors(&self) -> Vec<(&str, &str)> {
self.errors.iter()
.map(|(f, m)| (f.as_str(), m.as_str()))
.collect()
}
}
pub fn validation_errors_from_fields(errors: Vec<(String, String)>) -> ServiceError {
let error_map: std::collections::HashMap<String, Vec<String>> = errors.into_iter()
.fold(std::collections::HashMap::new(), |mut acc, (field, msg)| {
acc.entry(field).or_insert_with(Vec::new).push(msg);
acc
});
ServiceError::ValidationErrors(error_map)
}
pub fn validation_from_fields(errors: Vec<(&str, &str)>) -> ServiceError {
let converted: Vec<(String, String)> = errors.into_iter()
.map(|(field, msg)| (field.to_string(), msg.to_string()))
.collect();
validation_errors_from_fields(converted)
}