rustybook 0.2.0

An ergonomic Facebook client in Rust
Documentation
#[cfg(feature = "messenger")]
mod events;
mod user;

#[cfg(feature = "messenger")]
pub use events::EventCache;
pub use user::UserCache;

use crate::User;

/// In-memory cache for Rustybook runtime state.
#[derive(Debug)]
pub struct Cache {
    user: UserCache,
    #[cfg(feature = "messenger")]
    events: EventCache,
}

/// Trait for applying cache updates from incoming events.
pub trait CacheUpdate {
    /// The return type of an update.
    ///
    /// If there is nothing to return, specify this type as unit (`()`).
    type Output;

    /// Updates the cache with the implementation.
    fn update(&mut self, cache: &Cache) -> Option<Self::Output>;
}

impl Cache {
    /// Creates a cache with default limits.
    pub fn new() -> Self {
        Self {
            user: UserCache::new(None),
            #[cfg(feature = "messenger")]
            events: EventCache::new(),
        }
    }

    /// Creates a cache with an initial user.
    pub fn with_user(user: Option<User>) -> Self {
        Self {
            user: UserCache::new(user),
            #[cfg(feature = "messenger")]
            events: EventCache::new(),
        }
    }

    /// Returns the cached user.
    pub fn user(&self) -> Option<User> {
        self.user.get()
    }

    /// Updates cached user.
    pub fn set_user(&self, user: User) {
        self.user.set(user);
    }

    /// Returns cached message events.
    #[cfg(feature = "messenger")]
    pub fn messages(&self) -> Vec<crate::Message> {
        self.events.messages()
    }

    /// Caches incoming messenger event payloads.
    #[cfg(feature = "messenger")]
    pub fn update(&self, event: &mut rustybook_messenger::Event) {
        let _ = event.update(self);
    }

    #[cfg(feature = "messenger")]
    pub(crate) fn push_message(&self, message: crate::Message) {
        self.events.push_message(message);
    }
}

impl Default for Cache {
    fn default() -> Self {
        Self::new()
    }
}