Skip to main content

zulip_api/message/response/
base.rs

1use serde::{Deserialize, Serialize};
2use zeroize::Zeroize;
3
4use super::{ApiResult, ErrorCode};
5use crate::{impl_default, impl_display, impl_response};
6
7/// Represents the base response from a Zulip API server.
8#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, Zeroize)]
9pub struct BaseResponse {
10    msg: String,
11    result: ApiResult,
12    #[serde(skip_serializing_if = "Option::is_none")]
13    code: Option<ErrorCode>,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    ignored_parameters_unsupported: Option<Vec<String>>,
16}
17
18impl BaseResponse {
19    /// Creates a new [Self].
20    pub const fn new() -> Self {
21        Self {
22            msg: String::new(),
23            result: ApiResult::new(),
24            code: None,
25            ignored_parameters_unsupported: None,
26        }
27    }
28}
29
30impl_response!(BaseResponse);
31
32impl_default!(BaseResponse);
33impl_display!(BaseResponse);
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    use crate::response::Response;
39
40    #[test]
41    fn test_success_response() {
42        let msg = "test response";
43        let msg_json = serde_json::to_string(&msg).unwrap();
44
45        let result = ApiResult::Success;
46        let result_json = serde_json::to_string(&result).unwrap();
47
48        let response = BaseResponse::new().with_msg(msg).with_result(result);
49        let response_json = format!(r#"{{"msg":{msg_json},"result":{result_json}}}"#);
50
51        assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
52        assert_eq!(
53            serde_json::from_str::<BaseResponse>(&response_json).unwrap(),
54            response
55        );
56
57        assert_eq!(response.msg(), msg);
58        assert_eq!(response.result(), result);
59        assert_eq!(response.code(), None);
60    }
61
62    #[test]
63    fn test_error_response() {
64        let msg = "test response";
65        let msg_json = serde_json::to_string(&msg).unwrap();
66
67        let result = ApiResult::Error;
68        let result_json = serde_json::to_string(&result).unwrap();
69
70        let code = ErrorCode::BadRequest;
71        let code_json = serde_json::to_string(&code).unwrap();
72
73        let response = BaseResponse::new()
74            .with_msg(msg)
75            .with_result(result)
76            .with_code(code);
77        let response_json =
78            format!(r#"{{"msg":{msg_json},"result":{result_json},"code":{code_json}}}"#);
79
80        assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
81        assert_eq!(
82            serde_json::from_str::<BaseResponse>(&response_json).unwrap(),
83            response
84        );
85
86        assert_eq!(response.msg(), msg);
87        assert_eq!(response.result(), result);
88        assert_eq!(response.code(), Some(code));
89    }
90}