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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use prost::{DecodeError, EncodeError, Message};
use prost_types::Any;

use super::super::pb;
use super::super::{FromAny, IntoAny};

/// Used to setup the `field_violations` field of the `BadRequest` struct.
#[derive(Clone, Debug)]
pub struct FieldViolation {
    pub field: String,
    pub description: String,
}

impl FieldViolation {
    pub fn new(field: impl Into<String>, description: impl Into<String>) -> Self {
        FieldViolation {
            field: field.into(),
            description: description.into(),
        }
    }
}

/// Used to encode/decode the `BadRequest` standard error message.
#[derive(Clone, Debug)]
pub struct BadRequest {
    pub field_violations: Vec<FieldViolation>,
}

impl BadRequest {
    pub const TYPE_URL: &'static str = "type.googleapis.com/google.rpc.BadRequest";

    pub fn new(field_violations: Vec<FieldViolation>) -> Self {
        BadRequest { field_violations }
    }

    pub fn with_violation(field: impl Into<String>, description: impl Into<String>) -> Self {
        BadRequest {
            field_violations: vec![FieldViolation {
                field: field.into(),
                description: description.into(),
            }],
        }
    }
}

impl BadRequest {
    pub fn add_violation(
        &mut self,
        field: impl Into<String>,
        description: impl Into<String>,
    ) -> &mut Self {
        self.field_violations.append(&mut vec![FieldViolation {
            field: field.into(),
            description: description.into(),
        }]);
        self
    }

    pub fn is_empty(&self) -> bool {
        self.field_violations.is_empty()
    }
}

impl IntoAny for BadRequest {
    fn into_any(self) -> Result<Any, EncodeError> {
        let detail_data = pb::BadRequest {
            field_violations: self
                .field_violations
                .into_iter()
                .map(|v| pb::bad_request::FieldViolation {
                    field: v.field,
                    description: v.description,
                })
                .collect(),
        };

        let mut buf: Vec<u8> = Vec::new();
        buf.reserve(detail_data.encoded_len());
        detail_data.encode(&mut buf)?;

        Ok(Any {
            type_url: BadRequest::TYPE_URL.to_string(),
            value: buf,
        })
    }
}

impl FromAny for BadRequest {
    fn from_any(any: Any) -> Result<Self, DecodeError> {
        let buf: &[u8] = &any.value;
        let bad_req = pb::BadRequest::decode(buf)?;

        let bad_req = BadRequest {
            field_violations: bad_req
                .field_violations
                .into_iter()
                .map(|v| FieldViolation {
                    field: v.field,
                    description: v.description,
                })
                .collect(),
        };

        Ok(bad_req)
    }
}

#[cfg(test)]
mod tests {

    use super::super::super::{FromAny, IntoAny};
    use super::BadRequest;

    #[test]
    fn gen_bad_request() {
        let mut br_details = BadRequest::new(Vec::new());
        let formatted = format!("{:?}", br_details);

        println!("empty BadRequest -> {formatted}");

        let expected = "BadRequest { field_violations: [] }";

        assert!(
            formatted.eq(expected),
            "empty BadRequest differs from expected result"
        );

        assert!(
            br_details.is_empty(),
            "empty BadRequest returns 'false' from .is_empty()"
        );

        br_details
            .add_violation("field_a", "description_a")
            .add_violation("field_b", "description_b");

        let formatted = format!("{:?}", br_details);

        println!("filled BadRequest -> {formatted}");

        let expected_filled = "BadRequest { field_violations: [FieldViolation { field: \"field_a\", description: \"description_a\" }, FieldViolation { field: \"field_b\", description: \"description_b\" }] }";

        assert!(
            formatted.eq(expected_filled),
            "filled BadRequest differs from expected result"
        );

        assert!(
            br_details.is_empty() == false,
            "filled BadRequest returns 'true' from .is_empty()"
        );

        let gen_any = match br_details.into_any() {
            Err(error) => panic!("Error generating Any from BadRequest: {:?}", error),
            Ok(gen_any) => gen_any,
        };
        let formatted = format!("{:?}", gen_any);

        println!("Any generated from BadRequest -> {formatted}");

        let expected = "Any { type_url: \"type.googleapis.com/google.rpc.BadRequest\", value: [10, 24, 10, 7, 102, 105, 101, 108, 100, 95, 97, 18, 13, 100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, 95, 97, 10, 24, 10, 7, 102, 105, 101, 108, 100, 95, 98, 18, 13, 100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, 95, 98] }";

        assert!(
            formatted.eq(expected),
            "Any from filled BadRequest differs from expected result"
        );

        let br_details = match BadRequest::from_any(gen_any) {
            Err(error) => panic!("Error generating BadRequest from Any: {:?}", error),
            Ok(from_any) => from_any,
        };

        let formatted = format!("{:?}", br_details);

        println!("BadRequest generated from Any -> {formatted}");

        assert!(
            formatted.eq(expected_filled),
            "BadRequest from Any differs from expected result"
        );
    }
}