1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use actix_http::{Error, Response};
use actix_web::{HttpRequest, HttpResponse, Responder, ResponseError};
use futures_util::future::{ok, Ready};
use serde::Serialize;
use std::collections::HashMap;
use std::error::Error as StdError;

#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct ValidationError {
    field: String,
    errors: Vec<String>,
}

impl ValidationError {
    /// Get new validation error
    pub fn new() -> Self {
        ValidationError {
            field: "".to_string(),
            errors: vec![],
        }
    }

    /// Set validation error field name
    pub fn set_field_name(&mut self, name: &str) {
        self.field = name.to_string();
    }

    /// Add error code
    pub fn add(&mut self, error: &str) {
        self.errors.push(error.to_string());
    }

    /// Check if it already contains certain error code
    pub fn contains(&self, error_code: &str) -> bool {
        match self.errors.iter().position(|e| e.starts_with(error_code)) {
            Some(_) => true,
            _ => false,
        }
    }

    /// Check if validation error has anything to show
    pub fn has_errors(&self) -> bool {
        !self.field.is_empty() && self.errors.len() > 0
    }
}

#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct ValidationErrors {
    errors: HashMap<String, ValidationError>,
}

impl ValidationErrors {
    /// Create new validation errors holder
    pub fn new() -> Self {
        ValidationErrors {
            errors: HashMap::new(),
        }
    }

    /// Add validation error
    pub fn add(&mut self, error: ValidationError) {
        let name = error.field.clone();
        let mut e = error.clone();

        if self.errors.contains_key(&name) {
            e = self.errors.remove(&name).unwrap();

            for rule in &error.errors {
                if !e.contains(&rule) {
                    e.add(&rule);
                }
            }
        }

        if e.has_errors() {
            self.errors.insert(name, e);
        }
    }

    /// Check if there are any validation errors
    pub fn has_errors(&self) -> bool {
        self.errors.len() > 0
    }

    /// Copy single error from the hash map
    pub fn get_error(&self, key: &str) -> Result<ValidationError, ()> {
        if self.has_errors() && self.errors.contains_key(key) {
            match self.errors.get_key_value(key) {
                Some((_k, error)) => Ok(error.clone()),
                None => Err(()),
            }
        } else {
            Err(())
        }
    }

    /// Return all the errors
    pub fn get_errors(&self) -> HashMap<String, ValidationError> {
        self.errors.clone()
    }
}

/// Allow the use of "{}" format specifier
impl std::fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Implement std::error::Error for ValidationErrors
impl StdError for ValidationErrors {
    fn cause(&self) -> Option<&dyn StdError> {
        Some(self)
    }
}

/// Allow the error to be returned in actix as error response
impl ResponseError for ValidationErrors {
    fn error_response(&self) -> HttpResponse {
        HttpResponse::UnprocessableEntity().json(self)
    }
}

/// Allow the error to be returned into responder for actix right away
impl Responder for ValidationErrors {
    type Error = ValidationErrors;

    type Future = Ready<Result<Response, Self::Error>>;

    fn respond_to(self, _: &HttpRequest) -> Self::Future {
        let err: Error = self.into();
        ok(err.into())
    }
}