zulip-api 0.0.8

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

use crate::response::BaseResponse;
use crate::{field_access, impl_default, impl_display, impl_response};

/// Represents a response from the `Fetch API Key` Zulip endpoint.
///
/// Allows third-party applications to use a username-password authentication method.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, Zeroize)]
pub struct Response {
    #[serde(flatten)]
    base: BaseResponse,
    api_key: Option<String>,
    email: Option<String>,
    user_id: Option<i64>,
}

impl Response {
    /// Creates a new [Self].
    pub const fn new() -> Self {
        Self {
            base: BaseResponse::new(),
            api_key: None,
            email: None,
            user_id: None,
        }
    }
}

field_access! {
    Response {
        /// The API key that can be used to authenticate as the requested user.
        api_key: option_cow_deref { str, String },
        /// The email address of the user who owns the API key.
        email: option_cow_deref { str, String },
    }
}

field_access! {
    Response {
        /// The unique ID of the user who owns the API key.
        ///
        /// **Changes**: New in Zulip 7.0 (feature level 171).
        user_id: option { i64 },
    }
}

impl_default!(Response);
impl_display!(Response);
impl_response!(Response, base);

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

    #[test]
    fn test_response() {
        let api_key = "someLongApiKey";
        let api_key_json = serde_json::to_string(&api_key).unwrap();

        let email = "test_user@zulip.server";
        let email_json = serde_json::to_string(&email).unwrap();

        let user_id = 1;
        let user_id_json = serde_json::to_string(&user_id).unwrap();

        let req = Response::new()
            .with_api_key(api_key)
            .with_email(email)
            .with_user_id(user_id);

        let req_json = format!(
            r#"{{"msg":"","result":"success","api_key":{api_key_json},"email":{email_json},"user_id":{user_id_json}}}"#
        );

        assert_eq!(serde_json::to_string(&req).unwrap(), req_json);
        assert_eq!(serde_json::from_str::<Response>(&req_json).unwrap(), req);

        assert_eq!(req.api_key(), Some(api_key));
        assert_eq!(req.email(), Some(email));
        assert_eq!(req.user_id(), Some(user_id));
    }
}