Skip to main content

write

Function write 

Source
pub fn write<'a, T: Serialize + ?Sized>(
    ctx: &Ctx,
    key: &'a str,
    value: &T,
    ttl: Duration,
) -> impl Future<Output = Result<()>> + Send + use<'a, T>
Expand description

Stores value as JSON under key for ttl, replacing any previous value.

ttl must be at least MIN_TTL (60 seconds) and is truncated to whole seconds. Other locations may still read the old value for up to 60 seconds. Unlike fetch, a KV failure is an error, not a log line.

Free plan: one KV write (1,000 a day; one per second per key); none with STORE_VAR set to "null".

§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, ttl is below 60 seconds, or value does not serialize to JSON.
  • Error::Internal when KV rejects the write, e.g. past the daily limit (message prefixed with LOG_PREFIX).

§Examples

use std::time::Duration;

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

async fn refresh(State(ctx): State<Ctx>) -> Result<()> {
    let rates = Rates { eur: 0.92 }; // e.g. from a third-party API
    ocre::cache::write(&ctx, "rates:v1", &rates, Duration::from_secs(3600)).await
}