zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use core::fmt::Debug;

use fred::interfaces::KeysInterface;
use fred::prelude::Expiration;
use fred::prelude::RedisPool;
use fred::prelude::SetOptions;

use crate::core::redis_fred::create_pool;

#[derive(Clone)]
pub struct ReidsClient {
    pub client: RedisPool,
}

impl ReidsClient {
    pub async fn new(
        settings: &crate::core::redis_fred::RedisSettings,
    ) -> Result<Self, anyhow::Error> {
        Ok(Self {
            client: create_pool(settings).await?,
        })
    }

    pub async fn ttl(&self, key: &str) -> Result<i32, anyhow::Error> {
        Ok(self.client.next().ttl(key).await?)
    }

    pub async fn exists(&self, key: &str) -> Result<bool, anyhow::Error> {
        Ok(self.client.next().exists(key).await?)
    }

    pub async fn get<T>(&self, key: &str) -> Result<Option<T>, anyhow::Error>
    where
        T: serde::de::DeserializeOwned + Debug,
    {
        let val: Option<String> = self.client.next().get(key).await?;

        if let Some(val) = val {
            Ok(serde_json::from_str(&val)?)
        } else {
            Ok(None)
        }
    }

    pub async fn set<T>(&self, key: &str, value: &T, ttl_sec: usize) -> Result<(), anyhow::Error>
    where
        T: serde::Serialize + std::marker::Sync,
    {
        let serialized_data = serde_json::to_string(value)?;

        self.client
            .next()
            .set(
                key,
                serialized_data,
                Some(Expiration::EX(ttl_sec as i64)),
                Some(SetOptions::NX),
                false,
            )
            .await?;

        Ok(())
    }
}