Skip to main content

read

Function read 

Source
pub fn read<'a, T: DeserializeOwned>(
    ctx: &Ctx,
    key: &'a str,
) -> impl Future<Output = Result<Option<T>>> + Send + use<'a, T>
Expand description

The value under key, or None when it is absent, expired, unreadable as T, or when KV fails.

Never computes nor stores anything; pair it with write when fetch’s closure form does not fit. KV failures and values that no longer decode as T are logged with LOG_PREFIX and read as None.

Free plan: one KV read (100,000 a day), none when the request already read or wrote key, and none with STORE_VAR set to "null" (always None).

§Errors

  • Error::Internal (500) when the CACHE binding is missing, naming the fix: ocre g cache adds CACHE: bindings.kv(), to cloudflare.config.ts.
  • Error::Internal when key is empty or longer than 512 bytes.

§Examples

use axum::extract::State;
use ocre::{Ctx, Result};

async fn rate(State(ctx): State<Ctx>) -> Result<String> {
    let rates: Option<Rates> = ocre::cache::read(&ctx, "rates:v1").await?;
    Ok(rates.map_or_else(|| "unknown".to_owned(), |rates| rates.eur.to_string()))
}