Skip to main content

doido_cache/
fetch.rs

1//! Read-through caching (Rails `Rails.cache.fetch(key) { … }`).
2
3use crate::store::CacheStore;
4use doido_core::Result;
5use serde_json::Value;
6
7/// Return the cached value for `key`, or compute it with `render`, store it
8/// (with optional `ttl_secs`), and return it. `render` runs only on a miss.
9pub async fn fetch(
10    store: &dyn CacheStore,
11    key: &str,
12    ttl_secs: Option<u64>,
13    render: impl AsyncFnOnce() -> Value,
14) -> Result<Value> {
15    if let Some(value) = store.get(key).await? {
16        return Ok(value);
17    }
18    let value = render().await;
19    store.set(key, value.clone(), ttl_secs).await?;
20    Ok(value)
21}