File size: 1,649 Bytes
d8435ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
pub mod collections_api;
mod collections_common;
pub mod collections_internal_api;
pub mod points_api;
mod points_common;
pub mod points_internal_api;
pub mod raft_api;
pub mod snapshots_api;

use collection::operations::validation;
use tonic::Status;
use validator::Validate;

/// Validate the given request and fail on error.
///
/// Returns validation error on failure.
fn validate(request: &impl Validate) -> Result<(), Status> {
    request.validate().map_err(|ref err| {
        Status::invalid_argument(validation::label_errors("Validation error in body", err))
    })
}

/// Validate the given request. Returns validation error on failure.
fn validate_and_log(request: &impl Validate) {
    if let Err(ref err) = request.validate() {
        validation::warn_validation_errors("Internal gRPC", err);
    }
}

#[cfg(test)]
mod tests {
    use validator::Validate;

    use super::*;

    #[derive(Validate, Debug)]
    struct SomeThing {
        #[validate(range(min = 1))]
        pub idx: usize,
    }

    #[derive(Validate, Debug)]
    struct OtherThing {
        #[validate(nested)]
        pub things: Vec<SomeThing>,
    }

    #[test]
    fn test_validation() {
        use tonic::Code;

        let bad_config = OtherThing {
            things: vec![SomeThing { idx: 0 }],
        };

        let validation =
            validate(&bad_config).expect_err("validation of bad request payload should fail");
        assert_eq!(validation.code(), Code::InvalidArgument);
        assert_eq!(
            validation.message(),
            "Validation error in body: [things[0].idx: value 0 invalid, must be 1 or larger]"
        )
    }
}