Module repository

Module repository 

Source
Expand description

Data repository trait for abstracting database access.

The DataRepository trait decouples cache-kit from specific database implementations. This allows you to plug in any storage backend and makes testing your cache-using code straightforward via mockable implementations.

§Implementing DataRepository

Implement this trait for any storage backend:

  • SQL databases: SQLx, tokio-postgres, Diesel
  • NoSQL: MongoDB, DynamoDB, Firestore
  • In-memory: For testing (provided in this module)
  • Custom ORMs or proprietary systems

§Mocking for Tests

Create simple in-memory implementations for unit testing:

use cache_kit::repository::InMemoryRepository;
use cache_kit::entity::CacheEntity;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
pub struct User {
    id: String,
    name: String,
}

impl CacheEntity for User {
    type Key = String;
    fn cache_key(&self) -> Self::Key { self.id.clone() }
    fn cache_prefix() -> &'static str { "user" }
}

#[tokio::test]
async fn test_cache_with_mock_repo() {
    let mut repo = InMemoryRepository::new();
    repo.insert("user:1".to_string(), User {
        id: "user:1".to_string(),
        name: "Alice".to_string(),
    });

    // Use repo in your cache-kit code
    let user = repo.fetch_by_id(&"user:1".to_string()).await.unwrap();
    assert_eq!(user.map(|u| u.name), Some("Alice".to_string()));
}

§Error Handling

When implementing the trait for real databases, return Err for:

  • Database connectivity issues
  • Query timeouts
  • Authentication failures
  • Serialization errors
  • Any other storage operation failures

Structs§

InMemoryRepository
Simple in-memory repository for testing cache-kit implementations.

Traits§

DataRepository
Trait for data repository implementations.