Cache

Loco provides an cache layer to improve application performance by storing frequently accessed data.

Default Behavior

By default, Loco initializes a Null cache driver. This means any interaction with the cache will return an error, effectively bypassing the cache functionality.

Enabling Caching

To enable caching and configure a specific cache driver, you can replace the default Null driver with your preferred implementation.

In your app.rs file, define a function named after_context function as a Hook in the app.rs file and import the cache module from loco_rs.

Here's an example using an in-memory cache driver:

use loco_rs::cache;

async fn after_context(ctx: AppContext) -> Result<AppContext> {
    Ok(AppContext {
        cache: cache::Cache::new(cache::drivers::inmem::new()).into(),
        ..ctx
    })
}

Caching Items

All items are cached as &str values and keys.

use std::time::Duration;
use loco_rs::cache;

async fn test_cache(ctx: AppContext) {

    // insert an item into the cache
    ctx.cache.insert("key", "value").await;

    // insert an item into the cache that expires after a Duration
    ctx.cache.insert_with_expiry("key", "value", Duration::from_secs(300)).await;

    // retrieve an item from cache
    let value = ctx.cache.get("key").await.unwrap();
}

See the Cache API docs for more examples.