apolloconfig 0.1.0

apolloconfig
Documentation
use core::ops::Deref;
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

//
pub const NOTIFICATION_ID_INITIAL_VALUE: isize = -1;

//
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Notification {
    #[serde(rename = "namespaceName")]
    pub namespace_name: Box<str>,
    #[serde(rename = "notificationId")]
    pub notification_id: isize,
}

impl Notification {
    pub fn new(namespace_name: Box<str>, notification_id: isize) -> Self {
        Self {
            namespace_name,
            notification_id,
        }
    }
}

//
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Notifications(Vec<Notification>);

impl Deref for Notifications {
    type Target = Vec<Notification>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Notifications {
    pub fn new(map: HashMap<Box<str>, isize>) -> Self {
        Self(
            map.into_iter()
                .map(|(namespace_name, notification_id)| {
                    Notification::new(namespace_name, notification_id)
                })
                .collect::<Vec<_>>(),
        )
    }

    pub fn with_initial(namespace_names: &[Box<str>]) -> Self {
        Self(
            namespace_names
                .iter()
                .map(|namespace_name| {
                    Notification::new(namespace_name.to_owned(), NOTIFICATION_ID_INITIAL_VALUE)
                })
                .collect::<Vec<_>>(),
        )
    }

    pub fn update_notification_id(
        &mut self,
        namespace_name: Box<str>,
        notification_id: usize,
    ) -> bool {
        for notification in self.0.iter_mut() {
            if notification.namespace_name == namespace_name {
                notification.notification_id = notification_id as isize;
                return true;
            }
        }
        false
    }

    pub fn update_notification(&mut self, notification: &Notification) -> bool {
        self.update_notification_id(
            notification.namespace_name.to_owned(),
            notification.notification_id as usize,
        )
    }
}

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

    #[test]
    fn test_de() {
        //
        match serde_json::from_str::<Notifications>(include_str!(
            "../../tests/response_body_json_files/notifications_v2_ok.json"
        )) {
            Ok(notifications) => {
                println!("{:?}", notifications);
            }
            Err(err) => panic!("{}", err),
        }
    }
}