Skip to main content

hydracache_db/
entity.rs

1use hydracache::CacheKeyBuilder;
2
3/// Static cache metadata for a domain entity.
4///
5/// Derive or implement this trait when you want domain-shaped cache calls
6/// without repeating entity and collection names at every query site.
7///
8/// # Example
9///
10/// ```rust
11/// use hydracache_db::{CacheEntity, HydraCacheEntity};
12///
13/// #[derive(HydraCacheEntity)]
14/// #[hydracache(entity = "user", collection = "users", id = i64)]
15/// struct User;
16///
17/// assert_eq!(User::cache_key_for(&42), "user:42");
18/// assert_eq!(User::entity_tag_for(&42), "user:42");
19/// assert_eq!(User::collection_tag(), Some("users".to_owned()));
20/// ```
21pub trait CacheEntity {
22    /// Identifier type used to build entity keys and tags.
23    type Id: ToString;
24
25    /// Stable entity segment used in keys and entity tags.
26    const ENTITY: &'static str;
27
28    /// Optional collection tag for broader invalidation groups.
29    const COLLECTION: Option<&'static str>;
30
31    /// Build the logical cache key for this entity id.
32    fn cache_key_for(id: &Self::Id) -> String {
33        CacheKeyBuilder::new()
34            .entity(Self::ENTITY, id.to_string())
35            .build_string()
36    }
37
38    /// Build the entity invalidation tag for this id.
39    fn entity_tag_for(id: &Self::Id) -> String {
40        Self::cache_key_for(id)
41    }
42
43    /// Build the optional collection invalidation tag.
44    fn collection_tag() -> Option<String> {
45        Self::COLLECTION.map(|collection| CacheKeyBuilder::from_segment(collection).build_string())
46    }
47}