use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::hash::Hash;
pub trait CacheEntity: Send + Sync + Serialize + for<'de> Deserialize<'de> + Clone {
type Key: Display + Clone + Send + Sync + Eq + Hash + 'static;
fn cache_key(&self) -> Self::Key;
fn cache_prefix() -> &'static str;
fn serialize_for_cache(&self) -> Result<Vec<u8>> {
crate::serialization::serialize_for_cache(self)
}
fn deserialize_from_cache(bytes: &[u8]) -> Result<Self> {
crate::serialization::deserialize_from_cache(bytes)
}
fn validate(&self) -> Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
struct TestEntity {
id: String,
value: String,
}
impl CacheEntity for TestEntity {
type Key = String;
fn cache_key(&self) -> Self::Key {
self.id.clone()
}
fn cache_prefix() -> &'static str {
"test"
}
}
#[test]
fn test_serialize_deserialize() {
let entity = TestEntity {
id: "test_1".to_string(),
value: "data".to_string(),
};
let bytes = entity.serialize_for_cache().unwrap();
let deserialized = TestEntity::deserialize_from_cache(&bytes).unwrap();
assert_eq!(entity.id, deserialized.id);
assert_eq!(entity.value, deserialized.value);
}
#[test]
fn test_cache_key_generation() {
let entity = TestEntity {
id: "entity_123".to_string(),
value: "test".to_string(),
};
assert_eq!(entity.cache_key(), "entity_123");
assert_eq!(TestEntity::cache_prefix(), "test");
}
}