zulip-api 0.0.8

Client library for interacting with the Zulip API
Documentation
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

use super::{ApiResult, ErrorCode};
use crate::{impl_default, impl_display, impl_response};

/// Represents the base response from a Zulip API server.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, Zeroize)]
pub struct BaseResponse {
    msg: String,
    result: ApiResult,
    #[serde(skip_serializing_if = "Option::is_none")]
    code: Option<ErrorCode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ignored_parameters_unsupported: Option<Vec<String>>,
}

impl BaseResponse {
    /// Creates a new [Self].
    pub const fn new() -> Self {
        Self {
            msg: String::new(),
            result: ApiResult::new(),
            code: None,
            ignored_parameters_unsupported: None,
        }
    }
}

impl_response!(BaseResponse);

impl_default!(BaseResponse);
impl_display!(BaseResponse);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::response::Response;

    #[test]
    fn test_success_response() {
        let msg = "test response";
        let msg_json = serde_json::to_string(&msg).unwrap();

        let result = ApiResult::Success;
        let result_json = serde_json::to_string(&result).unwrap();

        let response = BaseResponse::new().with_msg(msg).with_result(result);
        let response_json = format!(r#"{{"msg":{msg_json},"result":{result_json}}}"#);

        assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
        assert_eq!(
            serde_json::from_str::<BaseResponse>(&response_json).unwrap(),
            response
        );

        assert_eq!(response.msg(), msg);
        assert_eq!(response.result(), result);
        assert_eq!(response.code(), None);
    }

    #[test]
    fn test_error_response() {
        let msg = "test response";
        let msg_json = serde_json::to_string(&msg).unwrap();

        let result = ApiResult::Error;
        let result_json = serde_json::to_string(&result).unwrap();

        let code = ErrorCode::BadRequest;
        let code_json = serde_json::to_string(&code).unwrap();

        let response = BaseResponse::new()
            .with_msg(msg)
            .with_result(result)
            .with_code(code);
        let response_json =
            format!(r#"{{"msg":{msg_json},"result":{result_json},"code":{code_json}}}"#);

        assert_eq!(serde_json::to_string(&response).unwrap(), response_json);
        assert_eq!(
            serde_json::from_str::<BaseResponse>(&response_json).unwrap(),
            response
        );

        assert_eq!(response.msg(), msg);
        assert_eq!(response.result(), result);
        assert_eq!(response.code(), Some(code));
    }
}