use std::future::Future; use std::time::Duration; use serde::Serialize; use serde::de::DeserializeOwned; use crate::error::{CacheError, CacheResult}; use crate::kv::Cache; impl Cache { pub async fn get_json(&self, key: &str) -> CacheResult> { match self.get_bytes(key).await? { Some(bytes) => Ok(Some(decode(key, &bytes)?)), None => Ok(None), } } pub async fn get_del_json(&self, key: &str) -> CacheResult> { match self.get_del::>(key).await? { Some(bytes) => Ok(Some(decode(key, &bytes)?)), None => Ok(None), } } pub async fn set_json(&self, key: &str, value: &T) -> CacheResult<()> { self.set(key, encode(key, value)?).await } pub async fn set_json_ex( &self, key: &str, value: &T, ttl: Duration, ) -> CacheResult<()> { self.set_ex(key, encode(key, value)?, ttl).await } pub async fn set_json_default(&self, key: &str, value: &T) -> CacheResult<()> { self.set_default(key, encode(key, value)?).await } pub async fn set_json_nx(&self, key: &str, value: &T) -> CacheResult { self.set_nx(key, encode(key, value)?).await } pub async fn set_json_nx_ex( &self, key: &str, value: &T, ttl: Duration, ) -> CacheResult { self.set_nx_ex(key, encode(key, value)?, ttl).await } pub async fn get_or_set_json( &self, key: &str, ttl: Option, fill: F, ) -> CacheResult where T: Serialize + DeserializeOwned, F: FnOnce() -> Fut, Fut: Future>, { if let Some(value) = self.get_json::(key).await? { return Ok(value); } let value = fill().await?; match ttl { Some(ttl) => self.set_json_ex(key, &value, ttl).await?, None => self.set_json(key, &value).await?, } Ok(value) } pub async fn mget_json( &self, keys: Vec, ) -> CacheResult>> { let raw: Vec>> = self.mget(keys.clone()).await?; raw.iter() .enumerate() .map(|(index, item)| match item { Some(bytes) => { let key = keys.get(index).map(String::as_str).unwrap_or_default(); Ok(Some(decode(key, bytes)?)) } None => Ok(None), }) .collect() } } pub(crate) fn encode(key: &str, value: &T) -> CacheResult> { serde_json::to_vec(value).map_err(|error| CacheError::encode(key, error)) } pub(crate) fn decode(key: &str, bytes: &[u8]) -> CacheResult { serde_json::from_slice(bytes).map_err(|error| CacheError::decode(key, error)) }